Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about instance variable scope, top-level vs. class

Tags:

ruby

I've been playing around with Ruby mostly in the top level and I typically write code like:

@x = 'foo'
def show_var
  puts @x
end

show_var # => foo

I thought that instance variables were available to both the Class and the Object, based off how this example works.

Today I ran into this, and it looks like my understanding of instance variables is incorrect:

class Test
  @x = "foo" #you would need to define this inside 'initialize' for this to be available to show_var
  def show_var
    puts @x
  end 
end

Test.new.show_var # => nil

It looks like the second example is how instance variables work. If you define an instance variable inside the Class, then it only exists inside that scope, and does not exist for instance methods.

Then my question is... why does the first case output 'foo' when the variable @x shouldn't exist inside the scope of an instance method? Also, what is the proper way for defining variables in the top-level Class that you want to use for your top-level methods?

like image 539
MichaelHajuddah Avatar asked Sep 02 '25 06:09

MichaelHajuddah


1 Answers

The method in the first example is at the top level. Which means it belongs to a special top level object main. You can't really create more copies of main, so self inside and outside of that method is the same. Check this out:

self # => main
def show_var
  self # => main
end

class Test
  self # => Test
  def show_var
    self # => #<Test:0x007fdf9c892d70>
  end 
end
like image 110
Sergio Tulentsev Avatar answered Sep 05 '25 01:09

Sergio Tulentsev