如何将静态Ruby代码转换为动态Ruby代码

Nav*_*wal 0 ruby

以下代码创建一个数组数组.每个数组的大小为5,可能的值范围为0到7.

arr = []
8.times do |n1|
  8.times do |n2|
    8.times do |n3|
      8.times do |n4|
        8.times do |n5|
          arr << [n1, n2, n3, n4, n5]
        end
      end
    end
  end
end
arr.size # => 32768
Run Code Online (Sandbox Code Playgroud)

如果8(in 8.times)和5(嵌套5次)是动态的,那么如何在不更改其功能的情况下将此代码转换为动态代码?例如,如果我必须得到一个大小为6而不是5的数组(如当前示例中所示),那么该代码应该如何重写?

Ily*_*lya 7

看来你正在寻找Array#repeated_permutation:

(0..7).to_a.repeated_permutation(5)
Run Code Online (Sandbox Code Playgroud)

让我们检查:

(0..7).to_a.repeated_permutation(5).size
#=> 32768
(0..7).to_a.repeated_permutation(5).first(10)
#=> [[0, 0, 0, 0, 0], 
#    [0, 0, 0, 0, 1], 
#    [0, 0, 0, 0, 2], 
#    [0, 0, 0, 0, 3], 
#    [0, 0, 0, 0, 4], 
#    [0, 0, 0, 0, 5], 
#    [0, 0, 0, 0, 6], 
#    [0, 0, 0, 0, 7], 
#    [0, 0, 0, 1, 0], 
#    [0, 0, 0, 1, 1]]
Run Code Online (Sandbox Code Playgroud)

注意:repeated_permutation返回Enumerator.