问题
In Ruby if i just assign a local variable.
sound = "bang".
is that a main.sound=("bang")
method? if so, where and how is that method "sound=" being defined? or how is that assignment working? if not, what is actually happening?
i know that for a setter method you would say x.sound=("bang"). and you are calling the method "sound=" on the object "x" with the argument "bang". and you are creating an instance variable "sound".
and i can picture all of that. but not when you assign a variable in the "main" object. as far as i know it isn't an instance variable of the Object class... or is it? I'm so confused.
回答1:
In most programming languages, Ruby included, assignment is a strange beast. It is not a method or function, what it does is associate a name (also called an lvalue since it's left of the assignment) with a value.
Ruby adds the ability to define methods with names ending in = that can be invoked using the assignment syntax.
Attribute accessors are just methods that create other methods that fetch and assign member variables of the class.
So basically there are 3 ways you see assignment:
- the primitive = operator
- methods with names ending in =
- methods generated for you by the attribute accessor (these are methods ending in =)
回答2:
A variable assignment is just creating a reference to an object, like naming a dog "Spot". The "=" is not calling any method whatsoever.
As @ZachSmith comments, a simple expression such as sound
could refer to a local variable named "sound"or a method of self
named "sound". To resolve this ambiguity, Ruby treats an identifier as a local variable if it has "seen" a previous assignment to the variable.
回答3:
is that a main.sound=("bang") method?
No. main.sound="bang"
should set instance variable or element of that variable.
With dot(main.sound
) you tell object to do some method(in this case sound
).
To manage local variables ruby create 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 doesn't know about a
. After you create your class, a
will soon disappear, deleted by garbage collector. However you can get that value using binding
method. It save local scope to some place and you can assign it to the variable.
bin.eval "a" # 42
lambda
s have scope where they were defined:
local_var_a = 42
lamb = ->{puts local_var_a}
lamb.call() # 42
来源:https://stackoverflow.com/questions/20934375/how-does-the-assignment-symbol-work-ruby