ohspite ohspite - 1 year ago 59
Ruby Question

Why is assignment treated differently in this single line conditional?

I've read a few things, including this and this, but I think the below example is different than what they're talking about. One person actually raises a similar example in the discussion but it's ignored.

So, run in irb (ignore the warnings about assignment in the conditional):

(puts x) if (x = 0) # NameError: undefined local variable or method `x'...
x # => 0
(puts x) if (x = 0) # "0", => nil

but the second time there's no error.

Does this make any sense, even in a "once you understand what the parser is really doing and that this just some optimization it all becomes clear" kind of way? Because to me, it seems pretty undesirable.

To be clear, the above conditional should be equivalent (right?) to

if newvar=0
puts newvar

which does not raise an error.

Update: There have been even more posts on this topic since this question was asked. For example,


Answer Source

Oddly enough, this works fine in Rubinius:

Welcome to IRB. You are using rubinius 1.2.4dev (1.8.7 7ae451a1 yyyy-mm-dd JI)
>> (puts x) if (x = 0) #=> nil

I'm inclined to say it's a weird parsing bug in MRI.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download