将.txt文件解析为Ruby中的键/值对

时间:2015-01-23 18:06:09

标签: ruby parsing text hash

我想知道是否有人可以帮助我并告诉我将以下文本(从.txt文件)解析为键值对的最佳方法

我必须处理的文字是:

"This is the Question Line"
"This is the Answer Line"

然后重复。我最简单的方法是解析这些行以及它们之后的所有行并将它们与Question和Answer键相关联?

2 个答案:

答案 0 :(得分:2)

你可以做到

array = []
# open the file in read mode. With block version you don'r need to
# worry about to close the file by hand. It will be closed when the
# read operation will be completed.
File.open('path/to/file', 'r') do |file|
  # each_line gives an Enumerator object. On which I'm calling
  # each_slice to take 2 lines at a time, where first line is the
  # question, and the second one is the answer. 
  file.each_line.each_slice(2).do |question, answer|
    array << {'Question' => question, 'Answer' => answer}
  end
end

答案 1 :(得分:0)

适当的红宝石方式可能是这样的:

data = Hash[['Question','Answer'].zip File.read('input.txt').split("\n")]