0

I am learning hashes and haven't figured out why it won't print the last line (capital_city).

more_states = {
  "Oklahoma": "OK",
  "Texas": "TX",
  "Colorado": "CO",
  "Kansas": "KS",
  "New Mexico": "NM"
}

puts "-" * 10
# Printing states and their abbreviations
more_states.each do |state, abbrev|
  puts "The abbreviation for #{state} is #{abbrev}"
end

more_cities = {
  "OK": "Oklahoma City",
  "TX": "Austin",
  "CO": "Denver",
  "KS": "Topeka",
  "NM": "Santa Fe"
}

puts "-" * 10
# Printing state abbreviations and the corresponding state capitals
more_cities.each do |abbrev, capital|
  puts "#{capital} is the capital of #{abbrev}"
end

puts "-" * 10
# Printing states, their abbreviations, and their capitals
more_states.each do |state, abbrev|
  capital_city = more_cities[abbrev]
  puts "The abbreviation for #{state} is #{abbrev}, and its capital is #{capital_city}"
end

My first two puts are working fine, but when I use puts within more_states.each, I'm unable to access more_cities.

I tried using more_cities.fetch also:

capital_city = more_cities.fetch(abbrev)

With this, I got an error that it can't find the key "OK" in more_cities, but that key is definitely in there.

Any suggestions? I feel like it's a syntax error, or I'm missing something.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
twoodou
  • 3
  • 3
  • Welcome to SO! Your keys are symbols but you're using strings. Try making the hashes with `=>` instead of `:` or use `more_cities[abbrev.to_sym]`. – ggorlen Apr 13 '20 at 02:37

1 Answers1

0

Key Type (String v Symbol)

The key in the more_cities is a symbol (e.g., :OK); however, in more_states the abbrev is a literal string (e.g., 'OK'). One solution is to convert the string to a symbol via the String.to_sym method.


Code Update

Notice the second line abbrev to abbrev.to_sym

more_states.each do |state, abbrev|
  capital_city = more_cities[abbrev.to_sym]  # <-- here
  puts "The abbreviation for #{state} is #{abbrev}, and its capital is #{capital_city}"
end



Supplemental

For more reading refer to these resources to describe a String v Symbol:

Mike
  • 1,279
  • 7
  • 18