Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you initialize variables in Ruby?

Are there any differences between the following ways of initialization of variables?

@var ||= []
@var = [] if @var.nil?
@var = @var || []

Please share your way initializing a variable and state the pros & cons.

like image 725
PeterWong Avatar asked Sep 06 '10 06:09

PeterWong


People also ask

How do you initialize a variable in Ruby?

Ruby Class Variables Class variables begin with @@ and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.

Why do we initialize variables in Ruby?

The initialize method is useful when we want to initialize some class variables at the time of object creation. The initialize method is part of the object-creation process in Ruby and it allows us to set the initial values for an object.

How do you initialize a string variable in Ruby?

str = '' , arr = [] , h = {} are the most common ways of initializing empty strings, arrays and hashes, respectively.


1 Answers

@var ||= [] and @var = @var || [] are equal it will set var to [] if it's false or nil

@var = [] if @var.nil? is more specific - will re-set var to [] only if it's equal to nil

like image 195
fantactuka Avatar answered Oct 05 '22 11:10

fantactuka