I have a curiosity with variable definition. I know about variable definition, it's just to understand how it works. The idea is to set myvar to 0 if it is not defined. I don't want to use false because false could be returned by false or nil.
def foo
myvar=1000
myvar = ((defined? myvar)==nil) ? 0 : myvar
puts myvar
end
foo # => 1000
but
def foo
# myvar=1000
myvar = ((defined? myvar)==nil) ? 0 : myvar
puts myvar
end
foo # => nil
but
def foo
mybool = ((defined? myvar)==nil)
myvar = mybool ? 0 : myvar
puts myvar
end
foo # => 0 it rocks !
It's like if the boolean test was affected to myvar before the final test was evaluated.
((defined? myvar)==nil)
gives 2 possibilities defined? myvar could be nil
or the right side of test nil
could be nil
(it's nil
).
To get rid of the nil part of this test, I tried this code :
def foo
mylocalvariable = 2 # it gives 'local-variable' and not nil
puts ((defined? myvar) == (defined? mylocalvariable ))
myvar = ((defined? myvar)!=(defined? mylocalvariable )) ? 0 : myvar
puts myvar
end
foo # => nil
It seems the first part of the test was affected to myvar, but assignment operators come after () or after comparison operator. Do you have an idea? I don't want an other code but just why it works like that. Thank you.