从哈希获取价值的不同方法

时间:2014-06-02 03:17:16

标签: ruby

为什么有不同的方法从哈希值中获取值?

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

1 个答案:

答案 0 :(得分:1)

使用HashWithIndifferentAccess

h = {"one" => 1, "two" => 2, "three" => 3}.with_indifferent_access

因为符号(如何调用:one)和字符串是不同的类。 Symbol文档。

<强>更新

对于我ActiveRecord,对象数组属性可以使用无关紧要的访问权限('name':name)。 但在你的情况下属性数组有字符串键。通常我们称它们为属性:user.name(我猜你知道这一点)。

也许你有一些旧版本的Rails,或者你没有使用Rails ActiveRecord,它可能是续集或其他东西。