To which object is a local variable assigned?

Viewed 358

For class variables, assigning klass.foo = 'bar' is really some syntastic sugar for calling the klass.foo=(bar) method. But if I assign a local variable like so:

irb(main):001:0> foo = 'bar'
=> "bar"

Then to which object is this variable assigned? Does this also call a foo= method somewhere? I would sort of expect this, because:

In Ruby, everything is an object. Every bit of information and code can be given their own properties and actions.

In my view, this would sort-of imply one (or perhaps a few) "magic" root object(s), under which everything else is defined (...but perhaps this mental image is wrong...)

I tried:

irb(main):002:0> Kernel.foo
NoMethodError: undefined method `foo' for Kernel:Module

irb(main):003:0> Object.foo
NoMethodError: undefined method `foo' for Object:Class

irb(main):004:0> self.foo
NoMethodError: undefined method `foo' for main:Object

The same applies to code such as:

def foo
    a = 'bar'
    puts self.a
end
foo

which gives me:

a.rb:3:in `foo': undefined method `foo' for main:Object (NoMethodError)
        from foo.rb:6:in `<main>'
3 Answers
Related