Ruby head-scratching magic:
irb(main):001:0> if falseBut now:
irb(main):002:1> x = true
irb(main):003:1> end
=> nil
irb(main):004:0> x
=> nil
irb(main):005:0> y
NameError: undefined local variable or method `y' for main:Object
from (irb):5
irb(main):006:0>
This here is very unusual, and I'm not sure if it is part of the Ruby specification or just the implementation. From what I gather, the declaration of 'x' is a side effect of the parsing of the conditional block. What other side effects to unexecuted code are there that we should know about?
The oddity does not carry over to the right side of assignment:
irb(main):001:0> if false
irb(main):002:1> x = y
irb(main):003:1> end
=> nil
irb(main):004:0> x
=> nil
irb(main):005:0> y
NameError: undefined local variable or method `y' for main:Object
from (irb):5
irb(main):006:0>
Why is the specification/implementation question important?
Because if we could rely on this behavior we could write more compact code, writing fewer variable declarations. For example:
if some_condition
x = true
end
#..
do_something if x
rather than:
x = nil
if some_condition
x = true
end
#..
do_something if x
if we can count on this in future and all implementations of Ruby.

0 comments:
Post a Comment