如何通过多个数组迭代以在Ruby中形成一对一映射

时间:2017-05-18 16:35:35

标签: ruby

我正在阅读下面的文件并根据标签分割值(值以制表符分隔)并分配给3个数组。

id_details.txt

id\a_po87y  Jack    leader
id\ruio66   John_Marsha leader_1
id\rzd766   123_Smart_option    fresher
id\ruio66   John_Marsha automation_dev
....
etc

3个阵列

id = ["id\a_po87y", "id\ruio66", "id\rzd766", "id\ruio66", etc..]

store = ["Jack", "John_Marsha", "123_Smart_option", "John_Marsha", etc...]

group = ["leader", "leader_1", "fresher", "automation_dev", etc...]

Jack_details.txt

Joined on Feb 7, 2016
Created by: Solomon (ruio66) 

[groups]
leader_1 = id\rty67, id\mztrt, id\ruio66, ncr\025kc, id\a_po87y
automation = id\bzo0l4, ccr\poxz7j
automation_dev = id\ruio66

John_Marsha_details.txt

Joined on Jan 7, 2016
Created by: Jack Rondon 

[groups]
leader_1 = id\sop0r2, id\34_dev, id\mz4d5, id\ruio66
fresher = id\kzpo98, id\gz8sl7, id\cp0jxr, id\fzxlol, 
automation_dev = id\ruio66

阅读文件 - Jack_details.txt (商店数组的第一个值)并转到行ID - leader (组数组的第一个值)并删除字符串 - id \ a_po87y (第一个值id数组)仅来自该行。

同样,检查文件中的行id - leader_1中的字符串 - id \ ruio66 - John_Marsha_details.txt并从该行中删除字符串。

必须对id_details.txt

中的所有条目执行相同操作

直接一对一的数组映射 - " id - >商店 - >组" 。凭借我的初级水平经验,我设法写下以下代码(不完整),我不知道如何达到我的要求。有什么建议让它起作用吗?提前谢谢。

file_dir = 'E:/ruby_work'

file = File.open("E:/ruby_work/id_details.txt", "r")
contents = file.each_line.map { |line| line.split("\t") }.transpose
id, file_name, group  = contents


id.each do |ids|
  puts "For ID: #{ids}"
  file_name.each do |name| 
   value = File.open("#{file_dir}/#{name}_details.txt")
   text = File.read(value)
   #puts text
   text.each_line do |el|
    group.each do |gr|
     if el.match(/#{gr}/) then 
      print "group row #{gr}\n"
      print "Its matching\n"
      replace = text.gsub( /#{Regexp.escape(ids)}\,\s/, '').gsub( /#{Regexp.escape(ids)}/, '' ).gsub /,\s*$/, ''
      else print "Not\n"
         print "group row #{gr}\n"
     end
     group.shift
    end 
   end
   file_name.shift
  end

 end  
id.shift

我得到的输出

For ID: id\a_po87y
Not
group row leader

Not
group row leader_1

For ID: id\ruio66

对长篇文章表示歉意,我希望我已正确地传达了这些要求。

0 个答案:

没有答案