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?
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.
||= 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.
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).
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.
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.
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