||= operator

Hi Nima,

What does the operator mean, and what is the difference between using
>>= and = ?

= is called the conditional assignment. It is essentially syntactic

sugar for (i.e. a shorter way of writing):

@my_time = @my_time || Time.now

The way this works is based on the behaviour of the OR (||) part of the assignment, and the general behaviour of statements in Ruby: statements always return something.

So, let's look at the following statement:

true || false

if you try this in irb you'll see the following:

>> true || false
=> true

irb tells us that Ruby returns false for the expression true || false. If we remember our boolean logic, we know this is the right answer.

However, where things start to get tricky is something like this:

>> true || "cheese"
=> true

>> false || "cheese"
=> "cheese"

>> "cheese" || "beef"
=> "cheese"

Notice how Ruby returns the value "cheese" in the second example above, and the first value in the third example (Ruby shortcuts the or, and knowing that true or anything is true, just returns the first value).

Now, as Ruby isn't statically typed, it lets us put anything on either side of the || operator. Now, the way it turns a standard object into true or false in order to evaluate the logic is as follows:

if the object is nil, or false, then it is represented as false.
if the object has any other value whatsoever, then it is represented as true.

So, knowing this, we can see how Ruby sees the string "cheese" as being true.

Now, returning back to the original question, we can see that:

@answer = false || "cheese"

would assign the value of "cheese" to answer.

Now, if we wrote:

@answer = @answer || "cheese"

then we get two possible behaviours:

1) if @answer has a value, then @answer is set to that value (basically this doesn't do anything)
2) if @answer doesn't exist, it is nil, which means that @answer will be set to "cheese" following the behaviour we've just seen.

Hope this helps,

Sam Aaron