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?
There're some quotes from the famous book Agile Web Development with Rails, which may be helpful to understand the symbol as well :
If you use
:foo => bar
, foo will be a symbol. The benefit to symbols is that they are unique. When you call on an item in the hash, you dohash[:foo]
.Symbols require less memory than strings, which also makes them useful if you want to make your program a little faster.
If you are familiar with Java, you might be aware that Strings in Java are immutable. Symbols are similar in that sense in Ruby. They are immutable, i.e., any number of occurances of a particular symbol
:symbol
will map to only a single memory address. And, hence, it is recommended to use symbols wherever possible since it optimizes memory usage.