多次迭代 [英] Multiple iterations
本文介绍了多次迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一个更容易,更清洁的方式来编写代码如下:
Is there a easier, cleaner way to write code like this:
(1..10).each do |i|
(1..10).each do |j|
(1..10).each do |k|
(1..10).each do |l|
puts "#{i} #{j} #{k} #{l}"
end
end
end
end
理想情况下我可以做类似...
Ideally I'd be able to do something like...
(1..10).magic(4) { |i, j, k, l| puts "#{i} #{j} #{k} #{l}" }
更好...
magic(10, 4) { |i, j, k, l| puts "#{i} #{j} #{k} #{l}" }
没有内置的东西,我该如何写一个像最后一个方法?
If there's not something built in, how would I write a method like the last one?
推荐答案
如果你是Ruby 1.9,您可以这样做:
If you're on Ruby 1.9, you can do this:
range = (1..10).to_a
range.repeated_permutation(4) do |set|
puts set.join(" ")
end
range = (1..10).to_a
range.product(range, range, range).each do |set|
puts set.join(" ")
end
这篇关于多次迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文