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?
Ruby symbols are created by placing a colon (:) before a word. You can think of it as an immutable string. A symbol is an instance of Symbol class, and for any given name of symbol there is only one Symbol object.
Double Colon :: is a very useful operator that allows constants, classes, or modules to access instance and class methods in Ruby programing language. This operator can access it from anywhere in the module and class.
The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module. Remember in Ruby, classes and methods may be considered constants too.
Ruby symbols are defined as “scalar value objects used as identifiers, mapping immutable strings to fixed internal values.” Essentially what this means is that symbols are immutable strings. In programming, an immutable object is something that cannot be changed.
:foo
is a symbol named "foo". Symbols have the distinct feature that any two symbols named the same will be identical:
"foo".equal? "foo" # false :foo.equal? :foo # true
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With