Reputation: 501
In Ruby, what's an elegant way to combine 2 strings from an array without repeating them? Example:
array = ['one', 'two', 'three', 'four']
And I want my output to be:
['onetwo', 'onethree', 'onefour', 'twothree', 'twofour', 'threefour']
Seems simple enough but I've been pretty stumped!
Edit: this is for doing something with anagrams so order does not matter. ('onetwo' ends up being equivalent to 'twoone'.)
Upvotes: 0
Views: 90
Reputation: 110745
You can use Arrary#combination, Enumerable#map and Array#join for that.
Code
array.combination(2).map(&:join)
#=> ["onetwo", "onethree", "onefour", "twothree", "twofour", "threefour"]
Explanation
array = ['one', 'two', 'three', 'four']
a = array.combination(2)
#=> #<Enumerator: ["one", "two", "three", "four"]:combination(2)>
To view the contents of the enumerator:
a.to_a
#=> [["one", "two" ], ["one", "three"], ["one" , "four"],
# ["two", "three"], ["two", "four" ], ["three", "four"]]
Then
a.map(&:join)
which has the same effect as:
a.map { |e| e.join }
#=> ["onetwo", "onethree", "onefour", "twothree", "twofour", "threefour"]
If you wanted "twoone"
as well as "onetwo"
, use Array#permutation instead of combination
:
array.permutation(2).map(&:join)
#=> ["onetwo" , "onethree", "onefour" , "twoone" , "twothree", "twofour",
# "threeone", "threetwo", "threefour", "fourone", "fourtwo" , "fourthree"]
Upvotes: 3