" Start your business on internet, we are here to help you "

We are Software Development and Technical Service providing company from kathmandu Nepal. We use latest technologies to fulfill your requirements

What is ||= (or-equals) operator in Ruby?

Ruby     Published at about 2 months ago    Bishnu Basyal

What is ||= (or-equals) operator in Ruby?

READ: Loops on Ruby Programming Language

In Ruby ||= (or-equals) is a "conditional assignment operator".

E.g. a ||= b

Simply, a ||= b means If a is undefined, nil or false, assign b to a. Otherwise, keep a intact.

a ||= b

is equivalent to

a || a = b

and not equivalent to

a = a || b

Ruby's short circuit evaluation means that if a is defined and evaluates to true, then the right hand side of the operator is not evaluated, and no assignment takes place.

This distinction is unimportant if a and b are both local variables, but is significant if either is a getter/setter method of a class.

 

Some examples:

> a ||= 1
=> 1
# a is undefined, so output is 1


> a ||= 2
=> 1
# a is defined, so right hand side of the operator is not evaluated, so output is 1

 

> foo = false
=> false

> foo ||= true
=> true
# foo is false, so foo is assigned true

> foo ||= false
=> true
# foo is true, right hand side of the operator is not evaluated

 

x ||= true  
=> true

x = false  
x ||= true  
=> true

you can try more........

A common misconception is that a ||= b is equivalent to a = a || b, but it behaves like a || a = b

READ: Basic data scraping using Ruby

Thank you.....

 

 

To Top