我已经读取了一个输入文件并将每列提取到各个数组中,如下所示。
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...]
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
我应该如何以嵌套的方式迭代数组,以便在文件Jack_details中检查数组的第一个元素 - ' id'(id \ a_po87y)的preence。 txt(商店数组的第一个元素)应该从行名称中删除 - leader(同样是组数组的第一个数组元素)
同样,应检查id \ ruio66在2dn文件中的可用性 - 行id中的John_Marsha - leader_1,如果存在,则删除它。
等......
id[0]--> store[0]-->group[0]
id[1]--> store[1]-->group[1]
and so on
我的代码,但数组元素中跳过了值
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
我做错了什么?
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
输出
For ID: id\a_po87y
Not
group row leader
Not
group row leader_1
For ID: id\ruio66
答案 0 :(得分:1)
如果我理解正确,也许你可以采取略微不同的方法:
考虑到这个
id[0]--> store[0]-->group[0] id[1]--> store[1]-->group[1]
然后您不需要嵌套循环,您可以尝试仅循环一次并使用索引从每个数组中获取每个值,如下所示:
(0..id.size - 1).each do |i|
puts "For ID: #{id[i]}"
value = File.open("#{file_dir}/#{file_name[i]}_details.txt")
text = File.read(value)
text.each_line do |line|
if line.match(/#{group[i]}/)
print "group row #{group[i]}\n"
print "Its matching\n"
replace = text.gsub(/#{Regexp.escape(id[i])}\,\s/, '')
.gsub(/#{Regexp.escape(id[i])}/, '')
.gsub(/,\s*$/, '')
else
print "Not\n"
print "group row #{group[i]}\n"
end
end
end
此代码假定id
,file_name
和group
的大小始终相同。