Using Ruby 2.3:
In example 1, the string key "a"
is automatically converted to a symbol, whereas with example 2, it stays a string.
Example 1
{"a": 1} # => {:a=>1}
Example 2
{"a"=>"c"} # => {"a"=>"c"}
I thought :
was the same as the old style hash rocket =>
syntax. What is going on? Why have I never noticed this in Rails? Is it the HashWithIndifferentAccess
that is obscuring this?
Symbols are most commonly used as placeholders in Hashes. We have used symbols already in Rails, for example the Rails params hash associates any the values of any parameters passed in by the user (from a form or in the url) with a symbol representing the name of that value.
Entries in a hash are often referred to as key-value pairs. This creates an associative representation of data. Most commonly, a hash is created using symbols as keys and any data types as values. All key-value pairs in a hash are surrounded by curly braces {} and comma separated.
#Symbols must be valid Ruby variable names and always start with a colon (:). In Ruby, symbols are immutable names primarily used as hash keys or for referencing method names. Recall that hashes are collections of key-value pairs, where a unique key is associate… We can also iterate over hashes using the .
In Ruby 2.3(.0), these are all the same:
{:"a" => 1} {"a": 1}, {:a => 1} {a: 1}
They all translate to the same thing: a
is a symbol in all these cases.
{"a"=>1}
is different: a
is a string in this case.
It's because of the new hash syntax introduced with ruby 1.9. The syntax with colon works with symbol keys only. It's called a "symbol to object" hash and it's only syntactic sugar for the most common style of hashes out there. Another point for me, it's closer to the javascript object notation.
If I have mixed key types then I prefer the old style (hash-rocket syntax), but that's up to you. Mixing the two style looks ugly to me.
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