On Monday 11 October 2010, egervari wrote:
|I was curious what “:” before a identifier was exactly. It seems that
|it’s often used as a map key… but what is it exactly?
|Printing :bob to the screen results in “bob”… but testing for
|equality between :bob and “bob” results in a falsehood.
|I figure this has to be some literal notation for something, but what?
It is a Symbol. Symbols are sequences of characters with the property
each sequence has a unique identity. This means that the symbol :abc
represented by the same object everywhere I use it. For example, in the
x = :abc
y = :abc
x and y contain the same object. This is unlike what happens with
where each string literal produces a new object:
x = ‘abc’
y = ‘abc’
x and y contain two strings with the same contents but different
you can see by using the object_id method).
Because of their properties, symbols are often used instead of strings
you’re not interested in the content of the string, but are only using
it as a
unique identifier. This is what happens in hashes.
As for the equality test, a string is not a symbol, so ‘bob’==:bob
You can learn more about the difference between strings and symbols
this mailing list for things like “difference between string and
|not the object references like it does in Java. Can you clear this up?
Ruby provides three methods to compare objects:
- equal? this method compares the identity of objects. That is,
(obj2) is true if and only if their object_id is the same. This method
defined in Object and shouldn’t (usually) be overridden
- == this method is used for comparing tow objects basing on their
For class Object, this is the same as equal? (comparing object
other classes may override it to give results basing on the objects’
For example, Array overrides this method to return true if the two
the same size and their contents are the same (according to the ==
- eql? this is a method used by hashes to check for the equality of
usually have the same meaning as ==, but some class change it. You
don’t need to change this
Your problem comes from the fact that you overrode the eql? method
the == method
|Ruby seems to @ in front of an identifier to denote that it’s an
|instance variable. I’m curious, what is the reason for this? And if
|these variables are in fact private to the object, is there some kind
|of short-hand to create getter/setters?, or do you have to define
|these 2 def’s yourself? I guess if that’s the case, it’s no worse than
|in Java, but Scala provides several ways to get around this. I’m
|curious if such shorthands exist.
Use the attr_reader, attr_writer and attr_accessor class methods. Attr
defines a getter method named as the instance variable, attr_writer
setter method named as the instance variable followed by an = and
attr_accessor does both. For example:
is the same as
def y= value
@y = value
def z= value
@z = value
I hope this helps