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.

Kevin Bedell
  • 13,254
  • 10
  • 78
  • 114

2 Answers2

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"]
steenslag
  • 79,051
  • 16
  • 138
  • 171
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("-")}
Kyle d'Oliveira
  • 6,382
  • 1
  • 27
  • 33
  • This does not give the desired result: `["foo", "foo-bar", "foo-bat", "bar-foo", "bar", "bar-bat", "bat-foo", "bat-bar", "bat"]` – Mischa Jun 05 '12 at 16:08
  • This does not handle cases that combine more than 2 elements. – Kevin Bedell Jun 05 '12 at 17:55
  • 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. – Kyle d'Oliveira Jun 05 '12 at 18:02