Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

{"user"=>
   {"bio"=>"rubyist",
   "created_at"=>"2011-05-03T15:21:46+02:00", 
   "email"=>"[email protected]", 
   "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.parse(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.

like image 495
Nerian Avatar asked May 03 '11 13:05

Nerian


3 Answers

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.

like image 137
sawa Avatar answered Apr 29 '23 11:04

sawa


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?

like image 28
diogoriba Avatar answered Apr 29 '23 12:04

diogoriba


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
like image 33
Mike Mazur Avatar answered Apr 29 '23 12:04

Mike Mazur