tags:

views:

64

answers:

3

I have the following hash:

{:charge_payable_response=>{:return=>"700", :ns2=>"http://ws.myws.com/"}}

How can I get the value of the key :return, which in this example is 700?

A: 

I would say it should be:

hash[charge_payable_response][return]

But, isn't return a reserved word in Ruby? That could cause a problem.

Peter
Hi Peter,Thanks for the quick reply, I wrote it like thisputs hash[:charge_payable_response][:ns2]then it works without a problem but, it is giving 0 as the return all the time..any idea what that itcheers,sameera
sameera207
got it working thanks for the help :D
sameera207
This won't work; `charge_payable_response` will be parsed as a method call.
Marc-André Lafortune
+3  A: 

If you have:

h = {:charge_payable_response=>{:return=>"700", :ns2=>"http://ws.myws.com/"}}

Then use:

h[:charge_payable_response][:return]
# => "700"

The colon prefix means that the key in the hash is a symbol, a special sort of unique identifier:

Symbol objects represent names and some strings inside the Ruby interpreter. They are generated using the :name and :"string" literals syntax, and by the various to_sym methods. The same Symbol object will be created for a given name or string for the duration of a program‘s execution, regardless of the context or meaning of that name. Thus if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts.

John Feminella
got it working thanks for the help :D
sameera207
+2  A: 

If:

data = { :charge_payable_response=> { :return=>"700", :ns2=>"http://ws.myws.com/" } }

Then to get the return value use:

data[:charge_payable_response][:return]
John Drummond
got it working thanks for the help :D
sameera207