新手问题 ruby 中 hash 列表的菜鸟问题

shlallen · January 24, 2013 · Last by cdrwin replied at January 25, 2013 · 2724 hits

小弟初学初学 ruby 请问在 hash 中,可以这样初始化一个 hash 列表 a={"a"=>1,"b"=>2}或者 a={:a=>1,:b=>2}, 请问这两者之间有什么区别,我知道的是在第一种初始化中,不能用 a[:a] 来访问元素,第二种不能用 a["a"] 来访问元素。

大神们,还望请教

不合语法吧

hash = { :a => 'b' }
hash = HashWithIndifferentAccess.new(hash)

#1 楼 @chenge 不好意思,打错了

#2 楼 @chucai 能详细一点吗

#4 楼 @shlallen 这种问题意义不大吧,避开这个写法就好了。

:a 是符号 "a" 是 String

:a != "a"

需要使用 HashWithIndifferentAccess

Unknow user #8 January 25, 2013

一个是字符串(String),一个是符号 (Symbol);两者肯定是不一样哦,一般推荐有 Symbol 吧

You need to Sign in before reply, if you don't have an account, please Sign up first.