-1

Possible Duplicate:
What does ||= (or equals) mean in Ruby?
RoR: Meaning of “user ||= User.new”

I saw it used in this Railscast:

@current_user ||= User.find(session[:user_id]) if session[:user_id]
Community
  • 1
  • 1
Richard Burton
  • 2,230
  • 6
  • 34
  • 49

1 Answers1

1

in Ruby, we can write the following code to operate itself.

x += 1

this means equally

x = x + 1

In intialize process, we want set initial value to a variable only when it is nil or not exist.

For example,

a = a || initial_value

First, the left condition is evaluated. If a is evaluated as false, the right condition is evaluated and a is assigned initial_value.

And, we can rewrite

a = a || initial_value

as the following

a ||= initial_value
utwang
  • 1,474
  • 11
  • 16
  • 1
    It's actually `@current_user || @current_user = User.find(session[:user_id]) if session[:user_id]` if you read the Ruby source (meaning `||=` and `&&=` don't expand the same way as `+=` etc). See the link posted as a comment to the original question. – Michael Kohl Aug 19 '12 at 07:30
  • As Michael says, this is **wrong**. Please see [this answer for the correct expansion of `||=`](http://stackoverflow.com/a/2505285/211563). – Andrew Marshall Aug 19 '12 at 13:32
  • Sorry about that. I did some googling first. – Richard Burton Aug 19 '12 at 16:41