1

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?

2 Answers 2

7
h.inject([]) do |arr, (k,v)|
  arr + v.map {|x| [k,x] }
end
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.