Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this string key in a hash converted to a symbol?

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?

like image 958
Nona Avatar asked Apr 09 '16 07:04

Nona


People also ask

Can hashes have symbols?

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.

What is key and value in hash?

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.

How do you represent a hash in Ruby?

#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 .


2 Answers

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.

like image 105
Zabba Avatar answered Sep 30 '22 11:09

Zabba


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.

like image 37
guitarman Avatar answered Sep 30 '22 12:09

guitarman