n_x_l
n_x_l

Reputation: 1610

In Ruby, variable names are not objects. Why?

This came up in slide 6 of the 10 Things Every Java Programmer Should Know About Ruby talk.

Now, I reviewed some answers and the general consensus is that anything with value, not a mere pointer, is an object. I am confused by this. If a = 1, a would share methods with 1, and in fact they would have the same object_id. How is saying "a is an object" not accurate?

Upvotes: 1

Views: 118

Answers (1)

Chuck
Chuck

Reputation: 237080

What the slide says is correct: Variables are not objects. However, the second statement here — "anything with value, not a mere pointer, is an object" — doesn't even make sense in the context of Ruby, which doesn't have "mere pointers" distinct from "things with value/objects".

The thing is, the variable a doesn't share methods with the object 1. It it certainly not the same thing as 1, because otherwise if you later wrote a = 2, you'd completely obliterate the number 1! The variable is just a place that holds a reference to the object 1. You can't talk to this place like you could an object — for example, as you noted, variables don't have distinct object_ids. The only things you can do with a variable are talk to the object it references and reassign it with a reference to a different object. The variable itself is not an object, it's just a place to store a reference to an object.

Upvotes: 4

Related Questions