Tar_Tw45
Tar_Tw45

Reputation: 3222

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)?

Upvotes: 19

Views: 46100

Answers (2)

ennuikiller
ennuikiller

Reputation: 46965

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

hash[hash.keys.to_sym]

Upvotes: 4

not an ai
not an ai

Reputation: 1823

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

Upvotes: 25

Related Questions