Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

ruby - 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?

question from:https://stackoverflow.com/questions/36513996/why-is-this-string-key-in-a-hash-converted-to-a-symbol

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...