From: Stefano Crocco Date: 2009-01-13T06:02:53+09:00 Subject: Re: what's the rules re whether a Hash can use either a Symbol or String to reference the value??? Alle lunedì 12 gennaio 2009, Greg Hauptmann ha scritto: > Hi, > Getting confused with Hashes a bit. It seems sometimes I can use both a > Symbol or a String to get the value back, but other times the Symbol > doesn't work. Is there any rule re how to remember how Hash handles > setting and getting values uses Symbol / String? > > e.g. hash_variable[:amount] versus hash_variable["amount"] > > e.g. hash_var = {:amount => 10}, versus hash_var = {"amount" => 10) By itself, a hash distinguish between strings and symbols, so if an entry is stored under a string key, you'll only be able to retrieve it using a string key. If the entry has a symbol entry, then it can only be obtained using a symbol key: h ={'a' => 1, :b => 2} puts h['a'] # => 1 puts h[:a] # => nil puts h[:b] # => 2 puts h['b'] # => nil You can setup the hash so that it will work either with strings or symbols. For example: hash = Hash.new do |h, k| if k.is_a?(String) and h.has_key? k.to_sym then h[k] = h[k.to_sym] elsif k.is_a?(Symbol) and h.has_key? k.to_s then h[k] = h[k.to_s] else nil end end hash['a'] = 1 hash[:b] = 2 puts hash['a'] # => 1 puts hash[:a] # => 1 puts hash[:b] # => 2 puts hash['b'] # => 2 puts hash[1] # => nil See the documentation for Hash.new to see how passing it a block works. I hope this helps Stefano