Posted By

ariellephan on 12/14/11


Tagged

hash


Versions (?)

Function as Procedure in Method called on Hashes


 / Published in: Ruby
 

URL: http://ruby.learncodethehardway.org/book/ex41.html

Learn Ruby the Hard Way

  1. cities = {'CA' => 'San Francisco',
  2. 'MI' => 'Detroit',
  3. 'FL' => 'Jacksonville'}
  4.  
  5. cities['NY'] = 'New York'
  6. cities['OR'] = 'Portland'
  7.  
  8. def find(list, state) #state is index in hash map
  9. if list.include? state
  10. return list[state]
  11. else
  12. return "Not found."
  13. end
  14. end
  15.  
  16. # ok pay attention!
  17. cities[:seek] = method(:find) #put function as proc in methods of hash cities, where index is :seek
  18.  
  19. while true
  20. print "State? (ENTER to quit) "
  21. state = gets.chomp
  22.  
  23. break if state.empty?
  24.  
  25. # this line is the most important ever! study!
  26. puts cities[:seek].call(cities, state)
  27. end

Report this snippet  

You need to login to post a comment.