0

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".

RubyDude1012
  • 477
  • 1
  • 8
  • 14

6 Answers6

6

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
Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
3

Is it because you forgot the " ?

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

but you could just do

if key == officer.name
oldergod
  • 15,033
  • 7
  • 62
  • 88
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

This should work

Anthony Alberto
  • 10,325
  • 3
  • 34
  • 38
2
@hash.has_key?(officer.name) ? @hash[officer.name] : "no match"
saihgala
  • 5,724
  • 3
  • 34
  • 31
1

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.

Catnapper
  • 1,875
  • 10
  • 12
1

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
kacy hulme
  • 131
  • 1
  • 10