← Back to Ruby Operators

Colon

The single colon (:) character is all about symbols in Ruby.

We can define a symbol with a prefixing :.

> :one
=> :one

We can create symbols from strings which is useful when the symbol involves interpolation or wouldn't be valid due to having spaces.

> :"ruby"
=> :ruby
> :"ruby on rails"
=> :"ruby on rails"
> v = 8.0
=> 8.0
> :"ruby on rails #{v}"
=> :"ruby on rails 8.0"
> :'ruby on rails #{v}'
=> :"ruby on rails \#{v}"

We see similar behavior when creating a hash:

{ "hello": "world" }
=> {:hello=>"world"}

If the thing we are trying to key in a hash is not intended to be a symbol, then we better reach for the hash rocket.

> { "hello" => "world" }
=> {"hello"=>"world"}

When we have a hash that is keyed with symbols, we use those same symbols to reference its values.

> book = {title: 'An Immense World', author: 'Ed Yong'}
=> {:title=>"An Immense World", :author=>"Ed Yong"}
> book[:title]
=> "An Immense World"

References