10 Jul, 2009, Chris Bailey wrote in the 2nd comment:
Votes: 0
Conditional initialisation is one of my favorite things to use to be honest. It has a few gotcha's and it's usage isn't quite as intuitive (to programmers from other languages) as it could be, but it's very useful. One thing to note, is to watch when you WANT things to be nil or false.
a = nil a ||= 2 # a is now 2, even though it was already defined as nil. a = false a ||= true # a is now true, even though it was already defined as false.
Probably obvious to most, but it's something to consider.
10 Jul, 2009, David Haley wrote in the 3rd comment:
Votes: 0
In Lua, only nil and false are 'false' for the purposes of boolean expressions; in particular, 0 is not false in Lua. Therefore (0 or 1) will return 0. What does Ruby do here?
In Lua, only nil and false are 'false' for the purposes of boolean expressions; in particular, 0 is not false in Lua. Therefore (0 or 1) will return 0. What does Ruby do here?
Same. Only nil and false evaluate to false.
10 Jul, 2009, Chris Bailey wrote in the 5th comment:
Votes: 0
0 is also non-false in Ruby.
0 || 1 => 0
10 Jul, 2009, David Haley wrote in the 6th comment:
Votes: 0
I kind of like this behavior, because it forces you to think about existence of a value as a concept. I've always preferred testing things explicitly, e.g. while(foo > 0) instead of just while(foo). If you mean a boolean, use a boolean. Nice to see that Ruby is enlightened as well. :tongue:
10 Jul, 2009, Chris Bailey wrote in the 7th comment:
Votes: 0
Well it is supposed to be the language of least surprise. False, Nil and Nonexistant all kind of suggest the lack of something to me, 0 is still a number
I kind of like this behavior, because it forces you to think about existence of a value as a concept. I've always preferred testing things explicitly, e.g. while(foo > 0) instead of just while(foo). If you mean a boolean, use a boolean. Nice to see that Ruby is enlightened as well. :tongue:
Well it is supposed to be the language of least surprise. False, Nil and Nonexistant all kind of suggest the lack of something to me, 0 is still a number
True, but coming from most languages it would certainly be a surprise. :P
Specifically how it works is it returns the value of the first non-nil-non-false evaluated term.
d will have the value of 1 in this case because of a, b, and c the first evaluated non-nil-non-false term was b's value of 1.
All that being said–Here is an interesting use to initialize a variable only if the variable has no value.
In this case a is the value of the first non-nil-non-false term. If a is already initialized it would be a. Otherwise it's 1.
Here's a shortcut to do the same thing:
So we can extrapolate a few interesting uses that can make development faster.