Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I change the value of self?

Tags:

ruby

self

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?

like image 409
user3680688 Avatar asked Sep 14 '14 14:09

user3680688


2 Answers

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.

like image 160
Jaugar Chang Avatar answered Nov 11 '22 03:11

Jaugar Chang


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.

like image 25
newacct Avatar answered Nov 11 '22 01:11

newacct