许多嵌套的“for”循环取决于变量
我想根据变量中的值在其自身中放入尽可能多的 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
在每种情况下,“做某事”部分始终是相同的。区别仅在于其周期数。
I want to put as many for
cycles in themselfs depending of value in a variable.
For example, if the variable @var = 1
, I need to perform:
for letter1 in @range
do something
end
If the variable @var = 2
:
for letter1 in @range
for letter2 in @range
do something
end
end
If the variable @var = 3
for letter1 in @range
for letter2 in @range
for letter3 in @range
do something
end
end
end
Is there a smarter/less code way than this code below? I don't wanna repeat myself all over again.
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
That do something
part is always the same in each case. The difference is only how much cycles it is in.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该阅读有关递归的内容: http://en.wikipedia.org/wiki/Recursion_(computer_science )
它类似于:
f
是一个函数,它通过字母再次递归地调用自身。每个调用都有信息深度
,这意味着递归应该有多深。You should read about recursion: http://en.wikipedia.org/wiki/Recursion_(computer_science)
It is something like:
f
is a function, which goes through letter calling itself again recursively. Each call have infodepth
, which means, how more deep recursion should be.