Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why postfix `if` in Ruby work so strange

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?

like image 233
user3240646 Avatar asked Jul 28 '17 14:07

user3240646


2 Answers

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

like image 175
ndnenkov Avatar answered Sep 30 '22 18:09

ndnenkov


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.

like image 30
Ilya Vorontsov Avatar answered Sep 30 '22 19:09

Ilya Vorontsov