【发布时间】:2023-03-16 13:35:01
【问题描述】:
使用How can I read a file with Ruby?,读取文件然后一行一行地打印它。
但我的要求不同。
我有一个类似千行内容的txt文件。
ABC 123
XYZ 234
所以使用下面的代码,我可以打印整行。
File.open("input.txt", "r") do |infile|
while (line = infile.gets)
puts "#{counter}: #{line}"
counter = counter + 1
end
end
但我需要将 column1 分配给 A,将 column2 分配给 B:
File.open("input.txt", "r").each_line do |A B|
puts "#{A} has the value of #{B}"
end
我该怎么做。
一般来说,我需要一个像 bash 脚本一样的 ruby 函数:
#!/usr/bin/env bash
while read A B
do
echo "$A has the value of $B"
done < input.txt
【问题讨论】:
标签: ruby