-1

Can't find any article.

I know it means "assign value to variable if variable is nil"

But.. When it is best to use it?

I did not use it before. Now after someone told me it should be used - I started to add it whenever I'm setting any instance variable.

In other words - every time I assign @variable in any class - I do it like so:

@variable ||= 'whatever'

Is that a good practice? Now someone told me not to use it for boolean fields.

Serge Vinogradoff
  • 2,262
  • 4
  • 26
  • 42
  • 1
    It means "assign value to variable if variable is nil _or false or undefined_"; it's important, think about it – mdesantis Jun 05 '14 at 10:16
  • 1
    That's what it **does**, what it means, literally, is `@variable = @variable || 'whatever'` – Max Williams Jun 05 '14 at 10:49
  • You should not use this statement per default whenever you assign a variable. It is often used in cases in which a variable might be either already initialized or not. If it was initialized before, the variable keeps its old value, otherwise 'whatever' will be assigned. – Peter Sorowka Jun 05 '14 at 11:00

1 Answers1

0

It is basically call as caching object to a variable instead frequently creating the same object. For example if you are using user variable in more than one place, it should be something like below.

def user
  @user ||= User.find(1)
end
Mohanraj
  • 4,056
  • 2
  • 22
  • 24