Why postfix `if` in Ruby work so strange

Viewed 1026

I have a follows strange behaviour in Ruby:

var1.zero? if var1 = 1

NameError: undefined local variable or method var1 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?

3 Answers

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.

Related