Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Hash.new vs Hash literal

Tags:

ruby

hash

api

I am calling a 3rd party API (written in PHP) passing in some key/value pairs.

This code works :

h = Hash.new
h['first_name'] = "Firstname"
h['last_name'] = "Lastname"
APICall([h]) # Record gets created

This doesn't :

h = {'first_name' => "Firstname", 'last_name' => "Lastname"}
APICall([h]) # Record does not get created

When I dump the Hash to the console in both the instances I get the same data structure. So why is it that the first way works but the 2nd doesn't?

EDIT : Not sure if this matters but I am using Ruby 1.8.7p72 / Linux . Also one of the key/value pair is a Base64 encoded image string.

like image 487
Anand Shah Avatar asked Feb 21 '12 13:02

Anand Shah


1 Answers

as the documentation of class Hash states:

[](*args) public

Creates a new hash populated with the given objects. Equivalent to the literal { key => value, … }. In the first form, keys and values occur in pairs, so there must be an even number of arguments. The second and third form take a single argument which is either an array of key-value pairs or an object convertible to a hash.

Hash["a", 100, "b", 200]             #=> {"a"=>100, "b"=>200}
Hash[ [ ["a", 100], ["b", 200] ] ]   #=> {"a"=>100, "b"=>200}
Hash["a" => 100, "b" => 200]         #=> {"a"=>100, "b"=>200}

http://apidock.com/ruby/Hash/%5B%5D/class

So at least Hash[] should have the same behavior as {...}

like image 145
phoet Avatar answered Sep 30 '22 17:09

phoet