Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 以不同的方式迭代多个数组_Ruby_Algorithm - Fatal编程技术网

Ruby 以不同的方式迭代多个数组

Ruby 以不同的方式迭代多个数组,ruby,algorithm,Ruby,Algorithm,尽管我试图用Ruby解决这个问题,但我还是欢迎大家用其他语言提出建议,我可以把这些建议带回Ruby 我有任何数组: color = ["red", "green", "blue"] size = ["small", "medium", "large"] style = ["loose", "tight"] 我需要为每个可能的组合创建字符串。例如: "red small loose", "red small tight", "red medium loose", "red medium tigh

尽管我试图用Ruby解决这个问题,但我还是欢迎大家用其他语言提出建议,我可以把这些建议带回Ruby

我有任何数组:

color = ["red", "green", "blue"]
size = ["small", "medium", "large"]
style = ["loose", "tight"]
我需要为每个可能的组合创建字符串。例如:

"red small loose", "red small tight", "red medium loose", "red medium tight", "red large loose", "red large tight", "green small loose", etc...

我愿意接受任何建议。

如果数组数量不是太多(少于5个),您可以编写嵌套循环。半代码:

>> color.product(size, style).map { |strings| strings.join(" ") }
#=> ["red small loose", "red small tight", ..., "blue large tight"]
for x = 0; x < color.size; x ++
    for y = 0; y < color.size; y ++
        for z = 0; z < color.size; z ++
            return color[x] + size[y] + style[z]
            z = z+1
        y = y+1
    x = x+1
表示x=0;x

虽然我对Ruby一无所知,但这基本上是可行的。

如果数组数量不是太多(少于5个),您可以编写嵌套循环。半代码:

for x = 0; x < color.size; x ++
    for y = 0; y < color.size; y ++
        for z = 0; z < color.size; z ++
            return color[x] + size[y] + style[z]
            z = z+1
        y = y+1
    x = x+1
表示x=0;x

虽然我对Ruby一无所知,但这基本上是可行的。

Ruby为数组提供了
product
方法,或者您可以使用循环

color.each do |color|
  size.each do |size|
    style.each do |style|
      puts "#{color} #{size} #{style} "
    end
  end
end

Ruby为数组提供了
product
方法,也可以只使用循环

color.each do |color|
  size.each do |size|
    style.each do |style|
      puts "#{color} #{size} #{style} "
    end
  end
end

color.product(大小、样式)
将完成这项工作

color.product(大小、样式)
将完成这项工作

您所做的被称为笛卡尔积。有关更多详细信息,请参见此问题:您所做的工作称为笛卡尔积。关于更多细节,请参见这个问题:惯用迭代器:)惯用迭代器:)除了在Ruby中,我们确实避免使用
进行
循环,而且
++
不是运算符。这就是我将其作为半代码发布的原因。我假设任何语言的开发人员都可以将其转换为特定的需求。我的答案基本上是xdazz发布的。好吧,这似乎是一个安全的假设,它将“基本工作”,直到你阅读了所有关于“为什么
++
不能与Ruby一起工作?”的问题。除了在Ruby中,我们真的避免使用
进行
循环,
++
不是运算符。这就是为什么我将它作为半代码发布的原因。我假设任何语言的开发人员都可以将其转换为特定的需求。我的答案基本上是xdazz发布的。好吧,这似乎是一个安全的假设,它将“基本上工作”,直到你阅读了所有关于“为什么
++
不能与Ruby一起工作?”的问题。