On 12.01.2009 22:02, Stefano Crocco wrote:
> Alle luned=EC 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 =3D {:amount =3D> 10}, versus hash_var =3D {"amount" =3D=
> 10)
>=20
> By itself, a hash distinguish between strings and symbols, so if an ent=
ry is=20
> stored under a string key, you'll only be able to retrieve it using a s=
tring=20
> key. If the entry has a symbol entry, then it can only be obtained usin=
g a=20
> symbol key:
>=20
> h =3D{'a' =3D> 1, :b =3D> 2}
> puts h['a'] # =3D> 1
> puts h[:a]  # =3D> nil
> puts h[:b]  # =3D> 2
> puts h['b'] # =3D> nil
>=20
> You can setup the hash so that it will work either with strings or symb=
ols.=20
> For example:
>=20
> hash =3D Hash.new do |h, k|
>   if k.is_a?(String) and h.has_key? k.to_sym then h[k] =3D h[k.to_sym]
>   elsif k.is_a?(Symbol) and h.has_key? k.to_s then h[k] =3D 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=20
change them to Symbols.

Kind regards

	robert

--=20
remember.guy do |as, often| as.you_can - without end