Home > Uncategorized > Ruby Conditional Assigment Operator ||=

Ruby Conditional Assigment Operator ||=

Conditional Assignment Operator, ||=, allows you to set the value of a variable, if there is no previous value set to it. This is a shorthand for something like this:

def get_instance
  unless @car
    @car = Car.new
  end
end 

This code can be shorthand to :

def get_instance
    @car = @car || Car.new
end 

You can even further shorthand the method to:

def get_instance
    @car ||= Car.new
end 
Author: Abdul Basit Munda Categories: Uncategorized Tags:
  1. No comments yet.
  1. No trackbacks yet.

Spam Protection by WP-SpamFree