首页 > 解决方案 > Ruby:从文件中放入多行

问题描述

对,所以我有一个文件,我想在其中获取两个不同的字符串

文本.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

标签: rubystringfile

解决方案


另一种更短的解​​决方案:

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

推荐阅读