tags:

views:

351

answers:

4

Can you explain me its meaning or give the link to the API page (which I couldn't find)?

+11  A: 
x ||= y

equals to

x = x || y

no?

It is used for "if x is not defined or otherwise empty, then put y into x" (default value, for example).

alamar
One issue to be aware of is that if x is false y is evaluated.
Scott
This is wrong. Please read http://Ruby-Forum.Com/topic/151660/ and the links provided therein.
Jörg W Mittag
+2  A: 

It means or-equals to. It checks to see if the value on the left is defined, then use that. If it's not, use the value on the right. You can use it in Rails to cache instance variables in models.

A quick Rails-based example, where we create a function to fetch the currently logged in user:

class User > ActiveRecord::Base

  def current_user
    @current_user ||= User.find_by_id(session[:user_id])
  end

end

It checks to see if the @current_user instance variable is set. If it is, it will return it, thereby saving a database call. If it's not set however, we make the call and then set the @current_user variable to that. It's a really simple caching technique but is great for when you're fetching the same instance variable across the application multiple times.

Jamie Rumbelow
This is wrong. Please read http://Ruby-Forum.Com/topic/151660/ and the links provided therein.
Jörg W Mittag
A: 

Edge Rails has a method decorator called memoize for doing this for you. It's only really useful if you have an expensive calculation or database call.

Randito
+8  A: 

This question has been discussed so often on the Ruby mailinglists and Ruby blogs that there are now even threads on the Ruby mailinglist whose only purpose is to collect links to all the other threads on the Ruby mailinglist that discuss this issue.

Here's one: The definitive list of ||= (OR Equal) threads and pages

If you really want to know what is going on, take a look at Section 11.3.1.2 "Abbreviated assignments" of the Ruby Language Draft Specification.

As a first approximation,

a ||= b

is equivalent to

a || a = b

and not equivalent to

a = a || b

However, that is only a first approximation, especially if a is undefined. The semantics also differ depending on whether it is a simple variable assignment, a method assignment or an indexing assignment:

a    ||= b
a.c  ||= b
a[c] ||= b

are all treated differently.

Jörg W Mittag