A string is a primitive type; whenever you call the string, it has a new object id. A symbol is a referenced type; whenever you create a symbol, you create a pointer, which points to the value.
I stored symbols in variables:
var1 = :foo
var1.object_id # => 2598748
:foo.object_id # => 2598748
var2 = :foo
var2.object_id # => 2598748
var2 = "hello"
var2.object_id # => 70131755422100
How is it possible that I create a second variable var2
, and it has the same object id as var1
? I create a second element. Does it mean that variables are also pointers?
Both variables point to the symbol :foo
. The symbol :foo
is stored just once, right?
Two variables are created, so they should be in the memory, and they cannot be in the same place because they have different names. var1
and var2
need to be stored, so that I can call them later. I don't get how I can call them if they have the same object id. If someone can help me to understand this, I'd be thankful.