检查哈希键是否出现在一行中

时间:2012-08-06 20:13:48

标签: ruby hash

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

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

如果我有一个包含以下内容的文件:

February
January
March

我希望输出为:

2
1
3

有人能给我一些快速建议吗?

2 个答案:

答案 0 :(得分: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
}'

答案 1 :(得分: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