1

How to merge hash with array values to one array:

h = {
    one: ["one1", "one2"],
    two: ["two1", "two2"]
}

after merge should be:

["one1","one2","two1","two2"]
1
  • is the order important? or is ["two1", "two2", "one1", "two2"] acceptable? Commented Apr 18, 2013 at 12:39

2 Answers 2

2
h.values.flatten
# => ["one1", "one2", "two1", "two2"]

You can do the same for the keys, of course. The only reason you need flatten here is because the values are themselves arrays, so h.values alone will return [["one1", "one2"], ["two1", "two2"]].

Also, just as an FYI, merge means something different (and pretty useful) in Ruby.

If you want to make sure it flattens only one level (per @tokland's comment), you can provide an optional argument to flatten such as with flatten(1).

Sign up to request clarification or add additional context in comments.

3 Comments

nit-pick: flatten(1) is more precise.
@tokland Depends on the situation, as it's not currently clear that the OP wants to flatten one level. I'll add a note, though.
Yeah. My point is that flatten is overused. A lots of times we only need to flatten one level and still we call a recursive flat. Maybe the OP has nested arrays, but in this case he would (should've) put it in the example. Just a detail, nothing more.
2
h.flat_map &:last
=> ["one1", "one2", "two1", "two2"]

1 Comment

Good one. I am late to post. Due to fill the CAPTCHA of SO Are you Robot :(

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.