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?
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.
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.
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
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