Hi,
There’s one more thing, I also read the following statements;
Ruby’s hashes can use any object as a key, but Symbol objects are the
most commonly
used. Symbols are immutable, interned strings. They can be compared by
identity
rather than by textual content (because two distinct Symbol objects
will never have the
same content).
The statement, “because two distinct Symbol objects will never have
the same content” seems unclear to me.
Can’t I do the following?
books = {
:excellent => “Iacocca”,
:good => “Freakonomics”,
:bad => “The World is Flat”,
:ugly => “Guns, Germs and Steel”,
:sick => “Guns, Germs and Steel”
}
In that case, won’t two distinct Symbol objects, i.e. :ugly, and :sick
have the same content?
I’m sure there’s something wrong in the way I’m understanding this,
could someone please elaborate?
Thanks,
~Mayuresh
2008/8/18 Mayuresh K. [email protected]:
}
In that case, won’t two distinct Symbol objects, i.e. :ugly, and :sick
have the same content?
I’m sure there’s something wrong in the way I’m understanding this,
could someone please elaborate?
The symbols themselvs (:ugly and :sick) will always be distinct, not
the strings they act as keys for in the hash.
Farrel
In that case, won’t two distinct Symbol objects, i.e. :ugly, and :sick
have the same content?
I’m sure there’s something wrong in the way I’m understanding this,
could someone please elaborate?
The symbols themselvs (:ugly and :sick) will always be distinct, not
the strings they act as keys for in the hash.
More precisely, symbols with same value are shared and point to the same
objects in memory:
syms = [:foo, :bar, :baz, :foo, :baz]
syms.map { |s| s.object_id }
=> [148818, 161538, 161618, 148818, 161618]
So, if two symbols have the same value, they are actually the very same
object in memory. Therefore, two distinct Symbol objects must have
different
values.
Mayuresh K. [email protected] writes:
}
In that case, won’t two distinct Symbol objects, i.e. :ugly, and :sick
have the same content?
No, :ugly refers to (“has the content of”) the symbol :ugly, and :sick
refers to the symbol :sick. The fact that you’re using different
symbols as keys to equal values in some hash is irreleveant. What’s
meant by the original statement is:
There are no two symbols ! :x.equal?(:y) where :x.eql?(:y)