I have a follows strange behaviour in Ruby:
var1.zero? if var1 = 1
NameError
: undefined local variable or methodvar1
for main:Object
From the other side, if I do same thing in a standard if
, all works as expected:
if var1 = 1
var1.zero?
end
# => false
Anyone can describe how work postfix if
in Ruby?
Because if I ask you
Isn't my daughter cute...
you will interrupt me with
You have a daughter?
before I could finish my initial sentence which was
Isn't my daughter cute, this is her [showing picture]?
But if I ask you
[showing picture] This is my daughter, isn't she cute?
you can easily respond
No
This is because local variables are available after assignment (and it's done in the lexical order, not in execution order).
So condition clause of postfix-if doesn't change a list of available local variables available in its body. But actually it does an assignment. You can inspect it by ignoring an exception and checking var1
value:
var1.zero? rescue nil if var1 = 1
puts(var1)
Also you can notice that instance variables work in a different way: they doesn't raise an error about undefined variable.
For additional info please take a look at an issue in ruby bug-tracker.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With