key: value vs key :value in ruby?

Viewed 118

In associations, we usually do a :b (belongs_to :something). When we create a hash with symbol keys we usually do a: b. Having said that my question is what is the difference between the two syntax. Also is there any logic to memorize when to use which convention?

2 Answers

This isn't about convention, it's about syntax.

:something is a Symbol.

belongs_to :something is a method that is being sent to an implicit self while also omitting the parentheses. We can write it as follows to make that obvious:

self.belongs_to(:something)

:something is thus just an argument being passed to the method belongs_to.

In a Hash, we can use a Symbol as the key:

hash = { :something => "hello" }

Ruby introduced an alternative syntax in version 1.9 that can be used when the key is a symbol:

hash = { something: "hello" }

Both versions are equivalent.

The difference here is between method call and hash key. They look very similar and can easily be confused if you're not sure what you're looking for.

In your first example:

a :b

In long-form this is:

a(:b)

Where now that's clearly an argument (:b) to a method (a).

In the other form it's different:

a: b

Where if that's part of a method call like this:

f a: b

Then that actually means:

f(a: b)

Which in full form is:

f({ a: b })

Where that's a hash definition following the key: value style. Here :a is the key (Symbol) and b is the value (variable or method call).

You'll often see a: :b where you have symbol key and value.

To differentiate between these two forms when reading code have a look at where the code appears to get a sense of context. When writing code, always frame your thinking in terms of method calls and hash definitions more clearly.

Related