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.
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.
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:
Symbol
literals as the key of a Hash
literal: { foo: 42 } # the same as { :foo => 42 }
def foo(bar:) end
foo(bar: 42)
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" }
: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" }
.
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]