How the destination symbol works - Ruby

In Ruby, if I just assign a local variable.

sound = "bang". 

is the method a main.sound=("bang") ? if so, where and how is this sound = method defined? or how does this task work? if not, what actually happens?

I know that for the setter method you would say x.sound = ("bang"). and you call the "sound =" method on the "x" object with the argument "bang". and you create a sound instance variable.

and I can imagine it all. but not when you assign a variable to the "main" object. as far as I know, this is not an instance variable of the Object class ... or is it? I'm so confused.

+7
variable-assignment ruby attr-accessor
source share
3 answers

In most programming languages, Ruby is turned on, the purpose is a strange beast. It is not a method or function, what it does is associate a name (also called lvalue, since it is left from the destination) with the value.

Ruby adds the ability to define methods with names ending in = that can be invoked using assignment syntax.

Attribute attributes are simply methods that create other methods that retrieve and assign class member variables.

So basically there are 3 ways you see the purpose:

  • primitive = operator
  • methods with names ending in =
  • generated by the accessor attribute for you (these are methods ending in =)
+6
source share

Assigning variables simply creates a reference to the object, for example, calling the dog "Spot". "=" Does not call any method at all.

As @ZachSmith comments, a simple expression such as sound can refer to a local variable called β€œsound” or a self method called β€œsound”. To eliminate this ambiguity, Ruby treats the identifier as a local variable if it "saw" the previous assignment of the variable.

+1
source share

is that main.sound = ("bang") method?

Not. main.sound="bang" should set the instance variable or element of this variable.
With a dot ( main.sound ), you tell the object some method (in this case, sound ).

To manage local ruby ​​variables, create a new scope.

 class E a = 42 def give_a puts a end def self.give_a puts a end binding end bin_e = _ # on pry E.give_a # error E.new.give_a # error 

Both methods are not aware of a . After creating the class, a will disappear soon; it is deleted by the garbage collector. However, you can get this value using the binding method. It saves the local area in any place, and you can assign it to a variable.

 bin.eval "a" # 42 

lambda have the area in which they were defined:

 local_var_a = 42 lamb = ->{puts local_var_a} lamb.call() # 42 
0
source share

All Articles