On Thu, Dec 9, 2010 at 9:08 AM, Soichi Ishida
<soujiro0725+rubyforum / gmail.com> wrote:
> Hi. =A0I am a little confused with the use of ":" like,
>
> hash =3D { :water =3D> 'wet', :fire =3D> 'hot' }
> puts hash[:fire] # Prints: =A0hot
>
> in constructing the hash in this example, ":water" is the key for "wet".
> I understand that. =A0But what is the difference between "water" and
> ":water"?
>
> I am guessing that ":water" works as a variable...but not quite sure.

Not exactly.  Here's the difference:

irb(main):001:0> :water.class
=3D> Symbol
irb(main):002:0> "water".class
=3D> String

Also:

irb(main):003:0> :water =3D=3D "water"
=3D> false
irb(main):004:0> "water" =3D=3D :water
=3D> false
irb(main):005:0> :water.eql? "water"
=3D> false

And, more importantly:

irb(main):010:0> a =3D (1..4).map { :water }
=3D> [:water, :water, :water, :water]
irb(main):011:0> a.map {|o| o.object_id}
=3D> [247864, 247864, 247864, 247864]
irb(main):012:0> a.map {|o| o.object_id}.uniq
=3D> [247864]

whereas

irb(main):013:0> a =3D (1..4).map { "water" }
=3D> ["water", "water", "water", "water"]
irb(main):014:0> a.map {|o| o.object_id}
=3D> [135636242, 135636228, 135636214, 135636200]
irb(main):015:0> a.map {|o| o.object_id}.uniq
=3D> [135636242, 135636228, 135636214, 135636200]

In other words: the sequence :water always returns the same Symbol
instance while the sequence "water" (and 'water' also) create a new
instance all the time.  If you have a limited set of Hash keys the
symbol is more appropriate because it is more efficient.  If the
number of keys is large and changes often better use String (e.g. when
reading them from some external source).

Kind regards

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/