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.
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.
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.
str = '' , arr = [] , h = {} are the most common ways of initializing empty strings, arrays and hashes, respectively.
@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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With