Home » Ruby » Ruby: colon before vs after [duplicate]

Ruby: colon before vs after [duplicate]

Posted by: admin November 30, 2017 Leave a comment

Questions:

This question already has an answer here:

Answers:

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" }

Questions:
Answers:

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)
Questions:
Answers:

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

Questions:
Answers:

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]