From: Johnny Morrice Date: 2011-05-28T05:09:17+09:00 Subject: Re: Hash .each and different action for each key On Sat, 28 May 2011 04:44:20 +0900 Igor Nn wrote: > Hello - > I have a hash table of several items. > > What I would like to do is loop through the hash and do a different > action based on each unique key. > my_hash_table.each_pair do |k, v| > # Call a method if a hash key == "a" > # Call a different method if hash key == "b" > # Call a third method if a hash key == "c" > end What you ask for is this: funcs = {} funcs["a"] == lambda {|v| puts "method for key 'a' with value: #{v}"} my_hash_table = {} my_hash_table["a"] = "Hmmmmm!" my_hash_table.each_pair do |k, v| funcs[k].call v end Are you sure you want that? It smells way bad. It's incoherent. Is there any thing wrong with the hash values being objects which do what you want, in each case. E.g. class Car def drive puts "broom, broom!" end end class Moped def drive puts "nnnnnnnnn!" end end vehicles = {} vehicles["a"] = Car.new vehicles["b"] = Moped.new vehicles.each_value do |veh| veh.drive end Much more coherant. Abstracts detail of algorithm from loop body into objects in well defined manner. Can be extended to do different things. Cheers Johnny