views:

100

answers:

2

I have a structure like this:

{:foo => ['foo1', 'foo2'], :bar => ['bar1']}

Which I would like to have transformed into:

[[:foo, "foo1"], [:foo, "foo2"], [:bar, "bar1"]]

My current solution is imperative:

result = []
h.each do |k,v|
  v.each do |value|
    result << [k, value]
  end
end

While this works, I am certain that there is a much more elegant way to write this, but I can't figure it out. I would like to know what a function-oriented solution would look like?

A: 

How about something like this? I wish there were something to add a bunch of arrays together, but I don't know of any, so I implemented my own.

class Array
  def concatArrays # concatenates an array of arrays
    inject([]) {|acc, x| acc + x}
  end
end

h.collect{|k,v| v.collect{|value| [k,value]}}.concatArrays
newacct
+6  A: 
h.inject([]) do |arr, (k,v)|
  arr + v.map {|x| [k,x] }
end
sepp2k
So simple. Thanks!
troelskn