比较散列中的值并返回匹配的键

时间:2012-10-03 14:13:48

标签: ruby arrays ruby-on-rails-3 hash key-value-observing

我正在尝试查看哈希并将其值与现有字符串进行比较,然后在找到匹配项时我想输出其密钥。我试图在代码块中写这个并将结果输出到控制台。

officer.name = "Dave"

@hash = { "Tom" => "97", "Dave" => "98", "John" => "99" }

@hash.each { |key, value| do
    if #{key} == officer.name
        puts "id: #{value}"
    else
        puts "no match"
    end
}

现在我的控制台输出:

 id: 97
 no match
 id: 98
 no match
 id: 99
 no match

我试图让它只输出#{value}的值,基于匹配的#{key},在这种情况下是Dave。因此,对于上面的示例,我希望我的控制台只吐出数字98或“不匹配”。

6 个答案:

答案 0 :(得分:6)

这是哈希!您可以更有效地完成您的尝试:

officer.name = "Dave"

@hash = { "Tom" => "97", "Dave" => "98", "John" => "99" }

unless @hash.key?(officer.name) 
  puts "no match"
else 
  puts "id: #{@hash[officer.name]}"
end

答案 1 :(得分:3)

是不是因为你忘了“?

if "#{key}" == officer.name

但你可以做到

if key == officer.name

答案 2 :(得分:2)

officer.name = "Dave"

@hash = { "Tom" => "97", "Dave" => "98", "John" => "99" }

@hash.each do |key, value|
  if key == officer.name
    puts key
  else
    puts "no match"
  end
end

这应该有效

答案 3 :(得分:2)

@hash.has_key?(officer.name) ? @hash[officer.name] : "no match"

答案 4 :(得分:1)

按键进行哈希查找时,请避免使用#[]。赞成#fetch:

officer.name = "Dave"
@hash = { "Tom" => "97", "Dave" => "98", "John" => "99" }
puts @hash.fetch(officer.name, 'no match')

#fetch允许您指定除nil之外的默认值,这将防止哈希查找中的意外nils抛出非常常见的NoMethodError。

答案 5 :(得分:1)

这也有效。从原始帖子略微编辑。 它打印出每对的答案,但不确定答案所指的是哪一对。

officer = "Dave"

@hash = { "Tom" => "97", "Dave" => "98", "John" => "99" }

@hash.each do |key, value|
    if key == officer
    puts key
  else
    puts "no match"
  end
end