Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Ruby variable if it is not already defined

People also ask

How do you declare a variable in Ruby?

Ruby Local VariablesLocal variables begin with a lowercase letter or _. The scope of a local variable ranges from class, module, def, or do to the corresponding end or from a block's opening brace to its close brace {}.

What is undefined in Ruby?

The undefined method is also called the NoMethodError exception, and it's the most common error within projects, according to The 2022 Airbrake Error Data Report. It occurs when a receiver (an object) receives a method that does not exist.

Are all variables objects in Ruby?

A variable itself is not an object. "A variable in Ruby is just a label for a container. A variable could contain almost anything - a string, an array, a hash.


While x ||= value is a way to say "if x contains a falsey value, including nil (which is implicit in this construct if x is not defined because it appears on the left hand side of the assignment), assign value to x", it does just that.

It is roughly equivalent to the following. (However, x ||= value will not throw a NameError like this code may and it will always assign a value to x as this code does not -- the point is to see x ||= value works the same for any falsey value in x, including the "default" nil value):

if !x
  x = value
end  

To see if the variable has truly not been assigned a value, use the defined? method:

>> defined? z
=> nil                                                                  
>> z = nil                                                              
=> nil                                                                  
>> defined? z                                                           
=> "local-variable"                                                     
>> defined? @z                                                          
=> nil                                                                  
>> @z = nil                                                             
=> nil                                                                  
>> defined? @z                                                          
=> "instance-variable" 

However, in almost every case, using defined? is code smell. Be careful with power. Do the sensible thing: give variables values before trying to use them :)

Happy coding.


@variable ||= "set value if not set"

So false variables will get overridden

> @test = true 
 => true 
> @test ||= "test"
 => true 
> @test 
 => nil 
> @test ||= "test"
 => "test" 
> @test = false 
 => false 
> @test ||= "test"
 => "test" 

As you didn't specify what kind of variable:

v = v
v ||= 1

Don't recommend doing this with local variables though.

Edit: In fact v=v is not needed