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?
You can find a key that leads to a certain value with Hash#key . If you are using a Ruby earlier than 1.9, you can use Hash#index . Once you have a key (the keys) that lead to the value, you can compare them and act on them with if/unless/case expressions, custom methods that take blocks, et cetera.
Hash literals use the curly braces instead of square brackets and the key value pairs are joined by =>. For example, a hash with a single key/value pair of Bob/84 would look like this: { "Bob" => 84 }. Additional key/value pairs can be added to the hash literal by separating them with commas.
Ruby | Hash key() function Hash#key() is a Hash class method which gives the key value corresponding to the value. If value doesn't exist then return nil. Syntax: Hash.key()
A Ruby hash is a collection of unique keys and their values. They are similar to arrays but array use integer as an index and hash use any object type. They are also called associative arrays, dictionaries or maps. If a hash is accessed with a key that does not exist, the method will return nil.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With