Ruby—如何获取两个字符串数组,并返回一个包含其中所有项组合的数组,首先列出第一个项
我的目标是:Ruby—如何获取两个字符串数组,并返回一个包含其中所有项组合的数组,首先列出第一个项,ruby,arrays,Ruby,Arrays,我的目标是: first = ["on","in"] second = ["to","set"] 为此: ["onto", "onset", "into", "inset"] 我想用一种方法实现这一点,到目前为止,这是我能得到的最接近的方法: def combinations(array_one,array_two) results = [] array_one.each do |x| array_two.each do |y| res
first = ["on","in"]
second = ["to","set"]
为此:
["onto", "onset", "into", "inset"]
我想用一种方法实现这一点,到目前为止,这是我能得到的最接近的方法:
def combinations(array_one,array_two)
results = []
array_one.each do |x|
array_two.each do |y|
results << ["#{x}#{y}"]
end
end
results
end
def组合(阵列一、阵列二)
结果=[]
数组| 1.每个do | x|
数组| 2.每个都是| y|
结果这应该有效:
def combinations(first, second)
first.product(second).map(&:join)
end
combinations(%w(on in), %w(to set))
# => ["onto", "onset", "into", "inset"]
你试过了吗
这很好用,谢谢!不过我很好奇,如果不使用.product,您将如何解决此问题?@MichaelBart您的方法是正确的,但不是结果
first = ["on","in"]
second = ["to","set"]
first.product(second).map(&:join) #=> ["onto", "onset", "into", "inset"]