Ruby: colon before vs after

Ruby

Ruby Problem Overview


When using Ruby, I keep getting mixed up with the :.

Can someone please explain when I'm supposed to use it before the variable name, like :name, and when I'm supposed to use it after the variable like name:?

An example would be sublime.

Ruby Solutions


Solution 1 - Ruby

This has absolutely nothing to do with variables.

:foo is a Symbol literal, just like 'foo' is a String literal and 42 is an Integer literal.

foo: is used in three places:

  • as an alternative syntax for Symbol literals as the key of a Hash literal: { foo: 42 } # the same as { :foo => 42 }
  • in a parameter list for declaring a keyword parameter: def foo(bar:) end
  • in an argument list for passing a keyword argument: foo(bar: 42)

Solution 2 - Ruby

You are welcome for both, while creating Hash :

{:name => "foo"}
#or
{name: 'foo'} # This is allowed since Ruby 1.9

But basically :name is a Symbol object in Ruby.

From docs

> Hashes allow an alternate syntax form when your keys are always symbols. Instead of

options = { :font_size => 10, :font_family => "Arial" }

You could write it as:

options = { font_size: 10, font_family: "Arial" }

Solution 3 - Ruby

:name is a symbol. name: "Bob" is a special short-hand syntax for defining a Hash with the symbol :name a key and the string "Bob" as a value, which would otherwise be written as { :name => "Bob" }.

Solution 4 - Ruby

You can use it after when you are creating a hash.

You use it before when you are wanting to reference a symbol.

In Arup's example, {name: 'foo'} you are creating a symbol, and using it as a key.

Later, if that hash is stored in a variable baz, you can reference the created key as a symbol:

baz[:name]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFloatingRockView Question on Stackoverflow
Solution 1 - RubyJörg W MittagView Answer on Stackoverflow
Solution 2 - RubyArup RakshitView Answer on Stackoverflow
Solution 3 - RubyChuckView Answer on Stackoverflow
Solution 4 - RubyvgoffView Answer on Stackoverflow