Total Ruby noob. I’m going through Zed Shaw’s LRTHW, and I’m stuck on the Hash exercise. I can’t make any sense of this code, and can’t find anything on the web that looks like it.
cities = {'CA' => 'San Francisco', 'MI' => 'Detroit', 'FL' => 'Jacksonville'}
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
def find_city (map, state)
if map.include? state
return map[state]
else
return "Not found."
end
end
cities[:find] = method(:find_city)
while true
print "State? (Enter to quit) "
state = gets.chomp
break if state.empty?
puts cities[:find].call(cities, state)
end
Basically, I’m just stuck. I can’t make the connection between how I type in a state and it returns the city. Any dumbed down explanation would be greatly appreciated.
Here there are a hash (cities) with 3 pairs key => value
You can access that values by the key:
Now we add two new pairs.
The whole hash will be:
Now it’s defined a method called
find_city. It takes a hash and a key.Here there is the worst piece of Ruby code I’ve ever seen.
Ok, that code gets the method
find_cityand turns it into aMethodobject, which could be assigned to a variable. BUT, instead of using a normal local variable, it is stored in a value of thecitieshash!That object is similar to a method, but it’s an object instead of a method, and it must be called with
call(in Ruby 1.8.7).I will use a variable called
my_meth(it could be any name) to explain better.But, instead to use a variable, the original code stored the
Methodobject on thecitieshash. So, cities will be:So, you can access the
find_citythrucities[:find].call.