From: Robert Dober Date: 2008-04-06T18:01:59+09:00 Subject: Re: The ||= assignment operator On Sat, Apr 5, 2008 at 10:39 PM, Robert Dober wrote: > On Sat, Apr 5, 2008 at 10:02 PM, David A. Black wrote: > > > > Hi -- > > > > > > On Sun, 6 Apr 2008, Robert Dober wrote: > > > > > > > On Sat, Apr 5, 2008 at 7:57 PM, Joel VanderWerf > > wrote: > > > > > > > David A. Black wrote: > > > > > > > > > > > > > > > > > The only time this matters is with hashes that have default values. In > > > > > every other case, as far as I know, x = x || y also describes what's > > > > > happening. But the expansion which describes *every* case is x || x = > > > > > y. > > > > > > > > > > > > > > > > > > One other case (a very similar one) in which it matters is this: > > > > > > > > class C > > > > def x; @x || 5; end > > > > def x=(v); puts "assigning @x=#{v}"; @x = v; end > > > > end > > > > > > > > c = C.new > > > > c.x ||= 3 # no effect > > > > p c.x # 5 > > > > c.x = 2 # assigning @x=2 > > > > p c.x # 2 > > > > > > > > -- > > > > vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407 > > > > > > > > > > > > > > > Hmm I am not sure I believe you rushed your example a little bit > > > > > > c.x = c.x || a > > > and > > > c.x || c.x = a > > > seem to me having the same effect. > > > > > > > I don't think so: > > > > irb(main):017:0> c = C.new > > => # > > irb(main):018:0> c.x || c.x = 1 # 5 || c.x = 1 => 5 > > => 5 > > irb(main):019:0> c.instance_eval { @x } > > that is true but that point was difficult to see, and I preferred an > example which shows the difference from the "normal" object interface > although my code is of course perverted. and one cannot see the problem through the object interface either :( In an attempt to make things clear enough I will take Joel's code again: class << C = Class::new def x; @x || 5 end def get_x; @x end def x= v; @x=v end end C.get_x --> nil C.x ||= 42 C.get_x --> nil C.x || C.x = 42 C.get_x --> nil C.x = C.x || 42 C.get_x --> 5 Hurray I guess I finally got it. Thx for the enlightenment. Cheers Robert > > > => nil > > irb(main):020:0> c.x = c.x || 1 # c.x = 5 || 1 => c.x = 5 > > assigning @x=5 > > => 5 > > irb(main):021:0> c.instance_eval { @x } > > => 5 > > > > > > > > > > David > > > > -- > > Rails training from David A. Black and Ruby Power and Light: > > ADVANCING WITH RAILS April 14-17 New York City > > INTRO TO RAILS June 9-12 Berlin > > ADVANCING WITH RAILS June 16-19 Berlin > > See http://www.rubypal.com for details and updates! > > > > > > > > > > -- > http://ruby-smalltalk.blogspot.com/ > > --- > Whereof one cannot speak, thereof one must be silent. > Ludwig Wittgenstein > > -- http://ruby-smalltalk.blogspot.com/ --- Whereof one cannot speak, thereof one must be silent. Ludwig Wittgenstein