From: badboy Date: 2009-01-13T06:03:20+09:00 Subject: Re: what's the rules re whether a Hash can use either a Symbol or String to reference the value??? Greg Hauptmann schrieb: > 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) > > first: every time you call hash_var["amount"] a new string is created. But if you call with :amount, :amount will always be the same object. next: the default Hash class does not mix String- and Symbol-Keys. so hash_var[:amount] = 10 hash_var["amount"] = 11 hash_var[:amount] != hash_var["amount"] # => true but for example ActiveSupport (used in Rails) defines a class HashWithIndifferentAccess. there all Symbol-keys gets converted to a String, so that either :amount or "amount" point to the same entry. So if you want to know how to handle it, ask the variable for its class (if someone uses monkey-patching you will lose =P)