为什么将哈希中的此字符串键转换为符号? [英] Why is this string key in a hash converted to a symbol?

查看:63
本文介绍了为什么将哈希中的此字符串键转换为符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Ruby 2.3:

Using Ruby 2.3:

在示例1中,字符串键"a"自动转换为符号,而在示例2中,它保留为字符串.

In example 1, the string key "a" is automatically converted to a symbol, whereas with example 2, it stays a string.

示例1

{"a": 1}
# => {:a=>1} 

示例2

{"a"=>"c"}
# => {"a"=>"c"}

我认为:与旧式哈希火箭=>语法相同.到底是怎么回事?为什么我从未在Rails中注意到这一点?是HashWithIndifferentAccess掩盖了这一点吗?

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?

推荐答案

在Ruby 2.3(.0)中,这些都相同:

In Ruby 2.3(.0), these are all the same:

{:"a" => 1}
{"a": 1},
{:a => 1}
{a: 1} 

它们都翻译成同一件事:a在所有这些情况下都是一个符号.

They all translate to the same thing: a is a symbol in all these cases.

{"a"=>1}是不同的:在这种情况下,a是字符串.

{"a"=>1} is different: a is a string in this case.

这篇关于为什么将哈希中的此字符串键转换为符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆