Reputation: 6398
I learned that in Ruby an object is just a bunch of instance variables and a link to a class (Metaprogramming Ruby 2, The Pragmatic Bookshelf).
When I create a variable, I make an instance of a class and assign it a value. Am I wrong in thinking that this value is stored in the object as an instance variable? When I call instance_variables, none show up. Example:
str = "hello" # => "hello"
str.class # => String
str.instance_variables # => []
If str
is an object and it equals "hello"
, where is "hello"
stored?
Upvotes: 1
Views: 307
Reputation: 4970
A variable is not an object. It is a programming language construct that provides a way to refer to an object in your source code.
For example, in the code below, the initalization of b
does not create a new object, only a new variable that refers to an object:
2.3.0 :012 > a = 'a string'
=> "a string"
2.3.0 :013 > b = a
=> "a string"
Upvotes: 2
Reputation: 168199
Local variable str
that you made is not an instance variable.
If you create an instance variable, then that is stored in the object. However, it does not make sense to call instance_variables
on the variable itself. You should call it on the object on which it is stored (in this case the implicit main context).
@str = "hello"
instance_variables # => [:@str]
Upvotes: 0
Reputation: 211670
Some of the Ruby classes are, as Jan pointed out, special. What this means is the internals are implemented in C, not Ruby, so they're invisible to the usual reflection tools.
You can have a look inside the Ruby source to see how this plays out.
In the case of string there's no instance variable that stores the string, the string itself is where it's stored.
Upvotes: 0