Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby if vs end of the line if behave differently?

Tags:

ruby

Why doesn't this code work?

b if b = true

Error: undefined local variable or method `b'

But this does:

if b = true
    b
end

Shouldn't they be the same?

like image 230
elado Avatar asked Jun 13 '12 20:06

elado


People also ask

How to check if a condition is true in Ruby?

With an if statement you can check if something is true . But when you want to check for the opposite “not true” (false) there is two things you can do. You can reverse the value with ! . Remember, using unless in Ruby is just the reverse of using if.

What does |= mean in Ruby?

||= is called a conditional assignment operator. It basically works as = but with the exception that if a variable has already been assigned it will do nothing. First example: x ||= 10. Second example: x = 20 x ||= 10. In the first example x is now equal to 10.

How do I check if a variable is nil in Ruby?

In Ruby, you can check if an object is nil, just by calling the nil? on the object... even if the object is nil. That's quite logical if you think about it :) Side note : in Ruby, by convention, every method that ends with a question mark is designed to return a boolean (true or false).


2 Answers

This is a very good question. It has to do with the scoping of variables in Ruby.

Here is a post by Matz on the Ruby bug tracker about this:

local variable scope determined up to down, left to right. So a local variable first assigned in the condition of if modifier is not effective in the left side if body. It's a spec.

like image 111
Michael Papile Avatar answered Oct 29 '22 01:10

Michael Papile


In the first version as soon as k is hit, the parser pukes because it hasn't been seen yet.

In the second version, k is part of an assignment expression, and is parsed differently.

like image 31
Dave Newton Avatar answered Oct 29 '22 01:10

Dave Newton