Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get hash key and convert into string ruby

Example Hash

hash = {:key => ["val1", "val2]}

When I did this on rails 3.0.7, it was fine.

> hash.keys.to_s
 => "key"
> hash[hash.keys.to_s]
 => ["val1", "val2"]

But if I do this with rails 3.1.3, it isn't.

> hash.keys.to_s
 => [\"key\"]
> hash[hash.keys.to_s]
 => nil

Is this was because of the Rails version changed? and Is there any other way to turn hash key into a string that works with both version (or with rails 2 too)?

like image 414
Tar_Tw45 Avatar asked Jan 10 '12 18:01

Tar_Tw45


2 Answers

Did you upgrade Ruby as well as Rails? I think this is a change between 1.8 and 1.9

Try hash.keys.first.to_s (if there's always only one key) or hash.keys.join

like image 98
telent Avatar answered Oct 21 '22 12:10

telent


You simply need to convert it to a symbol instead of a string which is being more correct:

hash[hash.keys.to_sym]
like image 26
ennuikiller Avatar answered Oct 21 '22 13:10

ennuikiller