Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the colon operator in Ruby?

Tags:

symbols

ruby

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?

like image 213
LuxuryMode Avatar asked Jun 14 '11 00:06

LuxuryMode


People also ask

What does the colon do in Ruby?

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.

What do two colons mean in Ruby?

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.

What is :: in Ruby?

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.

What are symbols used for in Ruby?

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.


1 Answers

: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.

like image 71
Chris Jester-Young Avatar answered Oct 17 '22 11:10

Chris Jester-Young