When I say { :bla => 1, :bloop => 2 }
, what exactly does the :
do? I read somewhere about how it's similar to a string, but somehow a symbol.
I'm not super-clear on the concept, could someone enlighten me?
When I say { :bla => 1, :bloop => 2 }
, what exactly does the :
do? I read somewhere about how it's similar to a string, but somehow a symbol.
I'm not super-clear on the concept, could someone enlighten me?
In ruby each object has an unique object identifier, if you write
puts "hello".object_id
in your irb and hit return for 2 different times, you will get 2 different returning value,but if you write:hello.object_id
2 times you will only get the same one returning value. That should have explained the difference.Just to demonstrate some of the things mentioned in the answers:
Running it outputs:
So, comparing a string to a string using
equal?
fails because they're different objects, even if they are equal content.==
compares the content, and the equivalent checks with symbols are much faster.Both symbol tests are basically the same as far as speed. After 1,000,000 iterations there's only 0.004733 second difference, so I'd say it's a wash between which to use.
All these answers omit one extra tantalising detail.. if you stringify the symbol :foo, you get.. guess what.. the string "foo". Hence
Hence.. for Perl programmers.. it's Ruby's answer to the 'bare word'.
:foo
is a symbol named "foo". Symbols have the distinct feature that any two symbols named the same will be identical:This makes comparing two symbols really fast (since only a pointer comparison is involved, as opposed to comparing all the characters like you would in a string), plus you won't have a zillion copies of the same symbol floating about.
Also, unlike strings, symbols are immutable.
Symbols are a way to represent strings and names in ruby.
The main difference between symbols and strings is that symbols of the same name are initialized and exist in memory only once during a session of ruby.
They are useful when you need to use the same word to represent different things
It's a symbol. Basically, you are saying that the two elements of the hash have keys
bla
andbloop
, much as if you had used the strings"bla"
and"bloop"
. However, they take up less memory than strings and are easier to type.