对,所以我有一个文件,我想在其中获取两个不同的字符串
text.txt:
abc
def
ghi
jkl
abc
ghi
我将如何阅读并打印两行内容? 我目前在这里:
File.open(filename) do |f|
f.each_line do |line|
if line =~ /abc/
puts "Current things: #{line}"
end
end
end
我在想这样的事情(因此,obv无法正常工作)
File.open(filename) do |f|
f.each_line do |line,line2|
if line =~ /abc/ and line2 =~ /ghi/
puts "Current things: #{line} #{line2}"
end
end
end
我要离开这个吗?
预期输出:
Current things: abc ghi
答案 0 :(得分:1)
一个替代方案,更短的解决方案:
lines = File.foreach(filename, chomp: true).each_with_object([]) do |line, arr|
arr << line if line.match?(/abc|ghi/)
end
puts "Current things: #{lines.join(' ')}" if lines.any?
# => Current things: abc ghi abc ghi
如果您想要唯一的行:
require 'set'
lines = File.foreach(filename, chomp: true).each_with_object(Set.new) do |line, set|
set.add(line) if line.match?(/abc|ghi/)
end
puts "Current things: #{lines.to_a.join(' ')}" if lines.any?
# => Current things: abc ghi
答案 1 :(得分:0)
您可以使用数组存储匹配的行,然后在完成迭代后打印它们。
File.open(filename) do |f|
matching_lines = []
f.each_line do |line|
if line =~ /abc/ || line =~ /ghi/
matching_lines << line
end
end
puts "Current things: #{matching_lines.join(' ')}" unless matching_lines.empty?
end