在Ruby中,如何在不重复的情况下组合数组中的两个字符串?
在Ruby中,哪种优雅的方式可以组合一个数组中的两个字符串而不重复它们? 例如: 我希望我的输出是:在Ruby中,如何在不重复的情况下组合数组中的两个字符串?,ruby,Ruby,在Ruby中,哪种优雅的方式可以组合一个数组中的两个字符串而不重复它们? 例如: 我希望我的输出是: ['onetwo', 'onethree', 'onefour', 'twothree', 'twofour', 'threefour'] 看起来很简单,但我被难倒了 编辑:这是为了做一些与字谜,所以秩序并不重要。('onetwo'最终等同于'twoone'。)您可以使用,为此 代码 array.combination(2).map(&:join) #=> ["onetwo"
['onetwo', 'onethree', 'onefour', 'twothree', 'twofour', 'threefour']
看起来很简单,但我被难倒了
编辑:这是为了做一些与字谜,所以秩序并不重要。('onetwo'最终等同于'twoone'。)您可以使用,为此
代码
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.map { |e| e.join }
#=> ["onetwo", "onethree", "onefour", "twothree", "twofour", "threefour"]
如果您想要“twoone”
以及“onetwo”
,请使用而不是组合:
array.permutation(2).map(&:join)
#=> ["onetwo" , "onethree", "onefour" , "twoone" , "twothree", "twofour",
# "threeone", "threetwo", "threefour", "fourone", "fourtwo" , "fourthree"]
你可以使用,并且为此
代码
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.map { |e| e.join }
#=> ["onetwo", "onethree", "onefour", "twothree", "twofour", "threefour"]
如果您想要“twoone”
以及“onetwo”
,请使用而不是组合:
array.permutation(2).map(&:join)
#=> ["onetwo" , "onethree", "onefour" , "twoone" , "twothree", "twofour",
# "threeone", "threetwo", "threefour", "fourone", "fourtwo" , "fourthree"]
你可以使用,并且为此
代码
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.map { |e| e.join }
#=> ["onetwo", "onethree", "onefour", "twothree", "twofour", "threefour"]
如果您想要“twoone”
以及“onetwo”
,请使用而不是组合:
array.permutation(2).map(&:join)
#=> ["onetwo" , "onethree", "onefour" , "twoone" , "twothree", "twofour",
# "threeone", "threetwo", "threefour", "fourone", "fourtwo" , "fourthree"]
你可以使用,并且为此
代码
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.map { |e| e.join }
#=> ["onetwo", "onethree", "onefour", "twothree", "twofour", "threefour"]
如果您想要“twoone”
以及“onetwo”
,请使用而不是组合:
array.permutation(2).map(&:join)
#=> ["onetwo" , "onethree", "onefour" , "twoone" , "twothree", "twofour",
# "threeone", "threetwo", "threefour", "fourone", "fourtwo" , "fourthree"]
问题不清楚。是什么决定要包括'onetwo'
,而不是'twoone'
?这个问题并不清楚。是什么决定要包括'onetwo'
,而不是'twoone'
?这个问题并不清楚。是什么决定要包括'onetwo'
,而不是'twoone'
?这个问题并不清楚。是什么决定要包括'onetwo'
,而不是'twoone'
?