I need this Hash
{"peter" => ["apple", "orange", "mango"], "sandra" => ["flowers", "bike"]}
convert to this Array:
[["peter", "apple"], ["peter", "orange"], ["peter", "mango"], ["sandra", "flowers"], ["sandra", "bike"]]
Now I have got this solution
my_hash.inject([]){|ar, (k,v)| ar << v.map{|c| [k,c]}}.flatten(1)
But I believe here is more elegant solution with those zip or transpose magick 🙂
You are right to be suspicious about
Enumerable#injectsolutions. In Ruby,inject/reduceis somewhat abused, we must be careful and choose the right abstraction (map, select, zip, flatten…) if they fit the problem at hand. In this case:But if you want to use
Enumerable#zipdon’t let anyone stop you 😉And as @steenslag says, also:
So at the end we can write: