From: Robert Klemme Date: 2009-01-13T16:24:15+09:00 Subject: Re: what's the rules re whether a Hash can use either a Symbol or String to reference the value??? On 12.01.2009 22:02, Stefano Crocco wrote: > 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 IMHO there is a downside to assign to the hash in the block because that changes the Hash. This would not work with a frozen Hash for example. I'd probably rather adjust keys on insertion and retrieval, e.g. always change them to Symbols. Kind regards robert -- remember.guy do |as, often| as.you_can - without end