1

If I have an array in Ruby, like this:

["foo", "bar", "bat"]

How can I generate a new array with every combination of values?

I need the output to look like this:

["foo", "bar", "bat", "foo-bar", "foo-bat", "bar-bat", "foo-bar-bat"]

Order is unimportant. Also, I do not need both "foo-bar" and "bar-foo".

The original array may have up to 5-6 members.

2 Answers 2

5
ar = ["foo", "bar", "bat"]
p 1.upto(ar.size).flat_map {|n| ar.combination(n).map{|el| el.join('-')}}
#=>["foo", "bar", "bat", "foo-bar", "foo-bat", "bar-bat", "foo-bar-bat"]
Sign up to request clarification or add additional context in comments.

1 Comment

In ruby 1.9 you can use flat_map instead of map + flatten.
2

You can try looking at the cross product of the two arrays

arr = %w(foo bar bat)

arr.product(arr).collect{|el| el.uniq.join("-")}

3 Comments

This does not give the desired result: ["foo", "foo-bar", "foo-bat", "bar-foo", "bar", "bar-bat", "bat-foo", "bat-bar", "bat"]
This does not handle cases that combine more than 2 elements.
Ahh, you are correct. I misread your question. Not only did I only see pairs of elements, but I thought you needed both orders. I will leave this here though in case it helps anyeone else.

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.