Reputation: 477
I'm trying to look through a hash and compare it's values to an existing string and then when the match is found I want to output its key. I trying to write this in a code block and output the result to the console.
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
}
Right now my console outputs:
id: 97
no match
id: 98
no match
id: 99
no match
I'm trying to get it to output just the value of #{value} based on it's matching #{key}, which in this case would be Dave. So for the above example I want my console to spit just the number 98 or "no match".
Upvotes: 0
Views: 6046
Reputation: 141
this works too. slight edit from original post. it prints out answer for each pair though and doesn't identify which pair the answer refers to.
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
Upvotes: 1
Reputation: 1905
When doing hash lookups by key, avoid #[]. Favor #fetch instead:
officer.name = "Dave"
@hash = { "Tom" => "97", "Dave" => "98", "John" => "99" }
puts @hash.fetch(officer.name, 'no match')
#fetch allows you to specify a default value other than nil, which will prevent unexpected nils from hash lookups from throwing the all-too-common NoMethodError.
Upvotes: 1
Reputation: 70929
This is a hash! You can do what you attempt way more efficiently:
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
Upvotes: 6
Reputation: 10395
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
This should work
Upvotes: 2
Reputation: 15010
Is it because you forgot the " ?
if "#{key}" == officer.name
but you could just do
if key == officer.name
Upvotes: 3