From: 7stud -- Date: 2009-08-25T00:59:12+09:00 Subject: Re: Modules setting values to nil in unprocessed conditional Nate wrote: > Hi everyone. We're noticing some strange behavior when including > modules in classes. It seems that even if a conditional block is > forced to evaluate as false (and presumably not execute), assignments > in the conditional block are executed and set to nil. Here is an > example: > > ========================== > module Conundrum > def riddle > @riddle ||= 'mystery' > end > > def riddle=(new_val) > puts "Called riddle=" > @riddle = new_val > end > end > > class Test > include Conundrum > > def test > puts "Before: #{riddle}" > if true == false Inside test, self is equal to the Test instance you created here: > Test.new.test And this line: > puts "Before: #{riddle}" is equivalent to: > puts "Before: #{self.riddle}" However, when ruby parses this line: > riddle = 'solved!' ruby creates a local variable named riddle. As a result, when you get to this statement: > puts "After: #{riddle}" riddle is no longer equivalent to self.riddle. Instead riddle is just riddle; and riddle is a local variable that hasn't been assigned a value. For local variables that exist but have not been assigned a value, ruby returns nil for the value of the variable. Then the string interpolation calls nil.to_s which returns a blank string. -- Posted via http://www.ruby-forum.com/.