为什么有不同的方法从哈希值中获取值?
h = {"one" => 1, "two" => 2, "three" => 3}
puts h[:one] # prints nothing
puts h['one'] # prints 1
puts h["one"] # prints 1
和
h = Hash.new
h[:one] = 1
h[:two] = 2
h[:three] = 3
puts h[:one] # prints 1
puts h['one'] # prints nothing
puts h["one"] # prints nothing
和
h = Hash.new
h["one"] = 1
h["two"] = 2
h["three"] = 3
puts h[:one] # prints nothing
puts h['one'] # prints 1
puts h["one"] # prints 1
通常,单引号和双引号具有相同的行为,但冒号与它们不同。有没有解释?
修改
那么,我们可以认为来自Activerecord
的散列总是有字符串键吗?
例如,我有users
表,列user_name
。
user = User.find_by_id(123)
user_name = user[:user_name] # get nothing
user_name = user["user_name"] # get correct user_name
答案 0 :(得分:1)
h = {"one" => 1, "two" => 2, "three" => 3}.with_indifferent_access
因为符号(如何调用:one
)和字符串是不同的类。 Symbol文档。
<强>更新强>:
对于我ActiveRecord
,对象数组属性可以使用无关紧要的访问权限('name'
和:name
)。 但在你的情况下,是属性数组有字符串键。通常我们称它们为属性:user.name
(我猜你知道这一点)。
也许你有一些旧版本的Rails,或者你没有使用Rails ActiveRecord,它可能是续集或其他东西。