Ruby: colon before vs after [duplicate]
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.
Solution 1:
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 aHash
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:
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:
: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:
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]