开发者

What is the difference between using single quotes and double quotes to query a Hash in Ruby?

{"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"}}  

What is the difference between using double double quotes and single quotes?:

attributes = JSON.parse(last_response.body)["user"]
attributes = JSON.p开发者_如何转开发arse(last_response.body)['user']

It seems that the first case works, but the second case does not find any key. I don't understand why.


For the differences, there are already other good answers. I suspect that you do not have the one-byte single quote.

Maybe, you might have backquotes:

attributes = JSON.parse(last_response.body)[`user`]

or multibyte single quotes:

attributes = JSON.parse(last_response.body)[’user’]

If that's the case, they should be replaced by the one-byte single quotes.


In the case of a plain-text key like "user" it shouldn't really make any difference, it's strange it's not working indeed. But if your key is an expression like, say, "#{variable_here}", it won't be evaluated unless you're using double quotes. Is this the case?


One major difference between single quotes and double quotes in Ruby is that double quotes perform string interpolation, while single quotes don't:

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

In your case, when accessing a hash, it should make no difference:

ruby-1.9.2-p180 :003 > {'one' => 1}['one']
 => 1 
ruby-1.9.2-p180 :004 > {'one' => 1}["one"]
 => 1


That's strange, they should work the same way and do for me:

>> 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"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜