许多嵌套的`for`循环取决于变量

时间:2011-01-25 11:43:51

标签: ruby recursion nested-loops

我想根据变量中的值,在自己中放置尽可能多的for个循环 例如,如果变量@var = 1,我需要执行:

for letter1 in @range
  do something
end

如果变量@var = 2

for letter1 in @range
  for letter2 in @range
    do something
  end
end 

如果变量@var = 3

for letter1 in @range
  for letter2 in @range
    for letter3 in @range
      do something
    end
  end
end 

是否有比下面这段代码更聪明/更少的代码方式?我不想再重复一次。

if @var == 1
  for letter2 in @range
    do something
  end
elsif @var == 2
  for letter1 in @range
    for letter2 in @range
      do something
    end
  end
elsif @var == 3
  for letter1 in @range
    for letter2 in @range
      for letter3 in @range
        do something
      end
    end
  end 
end

do something部分在每种情况下始终相同。不同之处仅在于它的周期。

2 个答案:

答案 0 :(得分:3)

你应该阅读有关递归的信息:http://en.wikipedia.org/wiki/Recursion_(computer_science)
它类似于:

def f(depth,letters=[])
  if depth == 0
    do someting with letters
  else
    for letter in @range
      f(depth-1,letters+[letter])
    end
  end
end

f(@var)

f是一个函数,它通过字母再次递归调用自身。每次调用都有信息depth,这意味着递归的深度应该更多。

答案 1 :(得分:1)

@range.map{|x| x}.product(*([@range.map{|x| x}] * n)) do |*args|
  do_something_with(*args)
end