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?
Test.instance_variable_get(:@x)- the instance variable@xhas been defined on theTestclass (which is an object of typeClass) - it can take a while to realise what that means, but it's a key part of Ruby to understand this