{"user"=>
{"bio"=>"rubyist",
"created_at"=>"2011-05-03T15:21:46+02:00",
"email"=>"paul@pauldix.net",
"id"=>61, "name"=>"paul",
"updated_at"=>"2011-05-03T15:21:46+02:00"}}
使用双引号和单引号有什么区别?:
attributes = JSON.parse(last_response.body)["user"]
attributes = JSON.parse(last_response.body)['user']
似乎第一种情况有效,但第二种情况没有找到任何密钥。我不明白为什么。
答案 0 :(得分:7)
对于差异,已经有其他好的答案。我怀疑你没有单字节单引号。
也许,你可能有反引号:
attributes = JSON.parse(last_response.body)[`user`]
或多字节单引号:
attributes = JSON.parse(last_response.body)[’user’]
如果是这种情况,则应将它们替换为单字节单引号。
答案 1 :(得分:6)
在像“用户”这样的纯文本密钥的情况下,它应该没有任何区别,奇怪的是它确实不起作用。 但是如果你的密钥是一个表达式,例如“#{variable_here}”,除非你使用双引号,否则它不会被评估。是这种情况吗?
答案 2 :(得分:6)
Ruby中单引号和双引号之间的一个主要区别是双引号执行字符串插值,而单引号不执行:
ruby-1.9.2-p180 :001 > puts "one plus one is #{1 + 1}"
one plus one is 2
=> nil
ruby-1.9.2-p180 :002 > puts 'one plus one is #{1 + 1}'
one plus one is #{1 + 1}
=> nil
在您的情况下,访问哈希时,它应该没有区别:
ruby-1.9.2-p180 :003 > {'one' => 1}['one']
=> 1
ruby-1.9.2-p180 :004 > {'one' => 1}["one"]
=> 1
答案 3 :(得分:3)
这很奇怪,他们应该以同样的方式工作并为我做:
>> user = {"user"=>
.. {"bio"=>"rubyist",
.. "created_at"=>"2011-05-03T15:21:46+02:00",
.. "email"=>"paul@pauldix.net",
.. "id"=>61, "name"=>"paul",
.. "updated_at"=>"2011-05-03T15:21:46+02:00"}}.to_json
#=> "{"user":{"bio":"rubyist","created_at":"2011-05-03T15:21:46+02:00","email":"paul@pauldix.net","id":61,"name":"paul","updated_at":"2011-05-03T15:21:46+02:00"}}"
>> attributes = JSON.parse(user)["user"]
#=> {"bio"=>"rubyist", "created_at"=>"2011-05-03T15:21:46+02:00", "email"=>"paul@pauldix.net", "id"=>61, "name"=>"paul", "updated_at"=>"2011-05-03T15:21:46+02:00"}
>> attributes = JSON.parse(user)['user']
#=> {"bio"=>"rubyist", "created_at"=>"2011-05-03T15:21:46+02:00", "email"=>"paul@pauldix.net", "id"=>61, "name"=>"paul", "updated_at"=>"2011-05-03T15:21:46+02:00"