问题
How come I'm allowed to change "self" this way:
self.map! {|x| x*2}
Or this way:
self.replace(self.map {|x| x*2})
But not this way:
self = self.map {|x| x*2}
Why doesn't Ruby allow me to change the object that the "self" variable points to, but does allow me to change the object's attributes?
回答1:
Not an answer, just a clue.
a=[1,2]
=>[1,2]
a.object_id
=>2938
a.map!{|x| x*2}
=>[2,4]
a.object_id # different data but still the same object
=>2938
a.replace(a.map {|x| x*2})
=>[4,8]
a.object_id # different data but still the same object
=>2938
a = a.map{|x| x*2} # .map will create a new object assign to a
=>[8,16]
a.object_id #different object
=>2940
You can't change your self to another one.
回答2:
In Ruby, values and variables are references (pointers to objects). Assigning to a variable simply makes it point to a different object; it has no effect on the object the variable used to point to. To change an object, you must call a method (including property getters/setters) on it.
You can think of self
as a variable that points to the object the method was called on. If you could assign to it, you could make it point to another object. If you could do that, it would not alter the object the method was called on; instead, you would make it so that any following code in that method that uses self
would use that object, not the object the method was called on. This would be super confusing, because self
would no longer point to the object the method was called on, which is a basic assumption.
来源:https://stackoverflow.com/questions/25834446/why-cant-i-change-the-value-of-self