mardi 20 septembre 2016

Some questions about symbol and instance method in Ruby

I'm currently try to learn ruby on 'Learn Ruby The Hard Way' Here's my question...

The following code are from exercise 40:

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

I played around with the code, and finally understand how it works. But I still don't understand about two things:

first...

In about middle of the code, it defined a variable

cities[:find] = method(:find_city)

As what I know for now, the :(colon) declare a symbol. I want to know is it a better practice to name a variable as cities[:find] instead of using cities_find in this case?

I'm not quite sure what's the differences, or maybe it's much readable for most rubyist?

And the second one is also about the same line.

method(:find_city)

I know it allows me to call the find_city method. But again, why I have to put a colon before find_city? Does this code means parse the arguments I put in to symbols?

I'm a little bit confused...

Sorry for my poor English...

Anyway, thankyou for your help!




Aucun commentaire:

Enregistrer un commentaire