Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how and when are Ruby variables instantiated

from rails console:

development environment (Rails 3.2.9)
1.9.2p320 :001 > defined?(kol)
 => nil 
1.9.2p320 :002 > if 1==2
1.9.2p320 :003?>   kol = 'mess'
1.9.2p320 :004?>   end
 => nil 
1.9.2p320 :005 > defined?(kol)
 => "local-variable" 
1.9.2p320 :006 > kol
 => nil 

my question is, why the does variable kol get instantiated to nil even though the condition (1==2) fails?

like image 554
RailinginDFW Avatar asked Mar 30 '13 19:03

RailinginDFW


People also ask

How do you initialize a variable in Ruby?

Ruby Class VariablesClass 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.

How do instance variables work in Ruby?

An instance variable in ruby has a name starting with @ symbol, and its content is restricted to whatever the object itself refers to. Two separate objects, even though they belong to the same class, are allowed to have different values for their instance variables.


1 Answers

It has to do with the way the Ruby interpreter reads the code.

The assignment to the variable doesn't have to be executed; the Ruby interpreter just needs to have seen that the variable exists on the left side of an assignment. (Programming Ruby 1.9 & 2.0)

a = "never used" if false
[99].each do |i|
  a = i # this sets the variable in the outer scope
end
a # => 99

"Ruby interpreter creates the variable even though the assignment isn't actually executed." http://www.jacopretorius.net/2012/01/block-variable-scope-in-ruby.html

like image 102
Luís Ramalho Avatar answered Sep 19 '22 11:09

Luís Ramalho