0

我正在尝试逐行浏览文件,如果该行包含哈希键,我想打印该值。例如:

Months = { "January" => 1,
           "February" => 2,
           "March" => 3
         }

如果我有一个文件包含:

February
January
March

我希望输出为:

2
1
3

谁能给我一些快速的建议?

4

2 回答 2

2

假设数据结构如下:

data = 'Months = { "January" => 1,
  "February" => 2,
  "March" => 3
}'

这将扫描它以查找与月份名称相关的数字:

months_to_find = %w[January February March]
months_re = Regexp.new(
  '(%s) .+ => \s+ (\d+)' % months_to_find.join('|'), 
  Regexp::IGNORECASE | Regexp::EXTENDED
)
Hash[*data.scan(months_re).flatten]['January'] # => 1

魔法发生在这里:

months_re = Regexp.new(
  '(%s) .+ => \s+ (\d+)' % months_to_find.join('|'), 
  Regexp::IGNORECASE | Regexp::EXTENDED
)

它创建了这个正则表达式:

/(January|February|March) .+ => \s+ (\d+)/ix

将额外的月份添加到months_to_find.

如果数据更改为:

data = 'Months = { "The month is January" => 1,
  "The month is February" => 2,
  "The month is March" => 3
}'
于 2012-08-06T23:06:07.803 回答
1
months = { "January" => 1, "February" => 2, "March" => 3 }

File.open('yourfile.txt').each_line do |line|
  result = months[line.strip]
  puts result if result
end
于 2012-08-06T20:20:42.410 回答