From: Rick DeNatale Date: 2010-02-04T23:10:58+09:00 Subject: Re: hooking subscript operations in a hash On Thu, Feb 4, 2010 at 8:54 AM, Marnen Laibow-Koser wrote: > Ralph Shnelvar wrote: >> RN> Is env['X'] = 'Y' the same as env[]=('X','Y') ? >> RN> Since you defined a method with def []= so I think env[]=('X','Y') >> is >> RN> easier for understanding. >> >> First ... I think you meant >>   env[]={'X', 'Y'} >> (braces instead of parenthesis) > > But you are wrong.  It's just like any other method call: > object.method(args) > so > env.[]=('X', 'Y') > > But never do it this way.  env['X'] = 'Y' is far clearer. > >> >> The first form >>   env[]={'X', 'Y'} >> means >>   Create > > No.  It won't create env. > >> and/or replace a hash table > > Hash, not hash table. > >> called "env" and stuff it with an >> index of 'X' and a value of 'Y' >> >> The second form >>   env['X'] = 'Y' >> means >>   Take an existing hash table called "env" and add/replace the index 'X' >> in that table with the value 'Y' > > No.  The two forms are 100% equivalent. Actually more like only 99 44/100% equivalent. In cases where a 'setter' method returns a value other than the argument there's a subtle diference: class MyHash def []=(key, value) "Hey Look, No Hands!" end end mh = MyHash.new a = mh[1] = 2 a # => 2 b = mh.[]=(1, 2) b # => "Hey Look, No Hands!" Ruby sees mh[index]=value as an assignment, and compiles it to the equivalent of mh,[]=(index, value) a = value -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Twitter: http://twitter.com/RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale