What object is the local variable assigned to?

For class variables, the assignment is klass.foo = 'bar'indeed the syntactic sugar for the method call klass.foo=(bar). But if I assign a local variable as follows:

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

Then what object is assigned to this variable? Does this also call a method foo=? I would kind of expect this because:

In Ruby, everything is an object. Each piece of information and code can be provided with its own properties and actions.

In my opinion, this will mean one (or possibly several) β€œmagic” root object (s), under which everything else is defined (... but perhaps this mental image is erroneous ...)

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, for example:

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>'
+4
3

Ruby 4 : local, instance, class global.

def x
  a = 1+2
end

a - ; , , 3. , "" ( / - ruby).

irb. ( . spickermann , irb .)

Everything in ruby is an object , . , ( Method, "" - ). . ( ).

+5

. getter :

a = 1
a #=> 1

:

a = 1
self.a
#=> raises NoMethodError, because there is no `a` getter method defined on self.

: . IRB, main ( Object):

# in irb
foo = 'Hello World'
self
#=> main
self.class
#=> Object < BasicObject
local_variables
#=> [:foo, ... ]
+4

?

.

foo= -?

, .

Ruby . .

Variables themselves do not have a specific class. They just refer to some kind of object.

In my opinion, this will mean one (or possibly several) β€œmagic” root object (s), under which everything else is defined (... but perhaps this mental image is erroneous ...)

In a sense, you can say that some local variables are bound to an instance Binding. But the current binding is switched by context, and there is no deity object that holds them all.

+1
source

All Articles