Ruby Variable Visibility

If I declare @var in Ruby, each object of this class will have its own @var .

But what if I miss @ ? I mean, I declare a variable named var2 without @ . Do they share a variable or are they temporarily created?

+4
source share
4 answers

If a variable is declared without a domain prefix ( @ - instance, @@ - class or $ - global), then it is declared for the current region, that is:

 class Foo def boo @boo ||= 'some value' var ||= 40 puts "boo: #@boo var: #{var}" end def foo var ||= 50 puts "boo: #@boo var: #{var}" end end c = Foo.new c.boo # => boo: some value var: 40 c.foo # => boo: some value var: 50 def foo $var ||= 30 puts "$var: #$var" end foo # => $var: 30 puts "$var: #$var" # => $var: 30 %w[some words].each do |word| lol = word # blocks introduce new scope end puts lol # => NameError: undefined local variable or method `lol' for word in %w[some words] lol = word # but for loop not end puts lol # => words 
+5
source

Without @ it is discarded when the method in which it is executed is executed.

 class Foo def initialize @bing = 123 zing = 456 end def get_bing @bing end def get_zing zing end end foo = Foo.new foo.get_bing #=> 123 foo.get_zing #=> NameError: undefined local variable or method `zing' for #<Foo:0x10b535258 @bing=123> 

This shows that the @bing instance @bing saved with this instance. This value is available in any method in this instance.

But the local zing variable zing not saved (in most cases), and as soon as this method is executed, any local variables are discarded and are no longer available. When get_zing run, it searches for a local variable or method named zing and does not find it, because zing has left the initialize long ago.

+5
source

It will become a local variable that belongs to the local lexical domain.

Ref.

 class Foo def Bar @fooz = 1 end def Barz fooz = 2 end def test puts @fooz end end f = Foo.new f.Bar f.test f.Barz f.test 

Output:

 1 1 #not 2 
0
source

If you use a variable called var2 , it is local and only in scope in the construct where it is declared. I.e:

  • If you declared it as part of a method, it will be local to that method.
  • If you try to declare in the class definition, but outside of any method, it will raise a NameError value. For instance:
 class Foo bar = 2 end Foo.new NameError: undefined local variable or method 'bar' 
0
source

All Articles