Robert Brandin
Robert Brandin

Reputation: 191

Cleanly converting a {"key" => ["val1", "val2"]} hash into a {"key" => "val1", "key" => "val2"} hash in Ruby/Rails

I'm fairly new to Ruby/Rails, and I'm trying to figure out how to split a {"key" => ["val1", "val2"]} hash into a {"key" => "val1", "key" => "val2"} hash. I feel like I should flatten the hash and somehow build a new one up, but I'm unsure how to approach the problem. Thanks!

EDIT: Haha, shows how blinded I was by the trees to not see the forest. Can't believe I made such a silly mistake. Thanks to everyone who shook me awake.

Upvotes: 1

Views: 233

Answers (2)

Phrogz
Phrogz

Reputation: 303224

A Hash by definition cannot have the same key present more than once. Would you instead like an Array of arrays?

[['key','val1'],['key','val2']]

If so, and if every hash key is an array of values, then you can do this:

devalues = { a:[1,2,3], b:[4], c:[5,6] }
exploded = devalues.map{ |k,vs| ([k]*vs.length).zip(vs) }.flatten(1)
p exploded
#=> [[:a, 1], [:a, 2], [:a, 3], [:b, 4], [:c, 5], [:c, 6]]

Note that flatten(1) is Ruby 1.8.7+ only

Edit: Per Nakilon's comment below, this can be a hair simpler in Ruby 1.9.2+:

exploded = devalues.flat_map{ |k,vs| ([k]*vs.length).zip(vs) }

Edit: Or per @tokland's comment below, even shorter/better using Array#product:

exploded = devalues.flat_map{ |k,vs| [k].product(vs) }

Upvotes: 2

Jacob Relkin
Jacob Relkin

Reputation: 163238

You cannot have duplicate keys in a Hash.

Also, why in the world would you want to do this? IMHO the way you have it now is perfectly fine.

Upvotes: 3

Related Questions