在Ruby中,从数组中组合2个字符串而不重复它们的优雅方法是什么? 例如:
array = ['one', 'two', 'three', 'four']
我希望我的输出为:
['onetwo', 'onethree', 'onefour', 'twothree', 'twofour', 'threefour']
看起来很简单,但我一直很难过!
编辑:这是为了用字谜做某事,所以顺序无关紧要。 ('onetwo'最终相当于'twoone'。)
答案 0 :(得分:3)
您可以使用Arrary#combination,Enumerable#map和Array#join。
<强>代码强>
array.combination(2).map(&:join)
#=> ["onetwo", "onethree", "onefour", "twothree", "twofour", "threefour"]
<强>解释强>
array = ['one', 'two', 'three', 'four']
a = array.combination(2)
#=> #<Enumerator: ["one", "two", "three", "four"]:combination(2)>
查看枚举器的内容:
a.to_a
#=> [["one", "two" ], ["one", "three"], ["one" , "four"],
# ["two", "three"], ["two", "four" ], ["three", "four"]]
然后
a.map(&:join)
具有与以下相同的效果:
a.map { |e| e.join }
#=> ["onetwo", "onethree", "onefour", "twothree", "twofour", "threefour"]
如果您想要"twoone"
以及"onetwo"
,请使用Array#permutation代替combination
:
array.permutation(2).map(&:join)
#=> ["onetwo" , "onethree", "onefour" , "twoone" , "twothree", "twofour",
# "threeone", "threetwo", "threefour", "fourone", "fourtwo" , "fourthree"]