ruby - 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
解决方案
另一种更短的解决方案:
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
推荐阅读
- node-red - 在 Node-Red 中从 HTML 中提取字段
- hibernate - 使用带有非主键的 @ElementCollection 连接
- javascript - 如何使用 useState() 在二维数组中设置新值
- python - 多处理 TensorFlow 预测
- javascript - SvelteKit 无法导入 Onboard.js
- activejdbc - ActiveJDBC 模型的虚拟属性
- c++ - 未使用的 Visual Studio 变量 (4101) 有时没有警告
- r - 用于执行更新表的 R 脚本的 Cron 作业不起作用!(控制台中没有显示错误)
- python - 计算 Voronoi 图和凸包之间的所有交点
- r - 将模式添加到 ggplot 箱线图