我正在尝试解决来自 Seven Languages in Seven Weeks 的一个简单的 Ruby 问题
Print the contents of an array of sixteen numbers, four numbers at a time, using just
each
这是我想到的,可以用简单的方式完成还是改进它?
a = (1..16).to_a
i = 0
j = []
a.each do |item|
i += 1
j << item
if(i % 4 == 0)
p j
j = []
end
end
可以在一行中使用each_slice
a.each_slice(4){|x| p x}
最佳答案
Teja,你的解决方案没问题。由于您需要使用每一个,因此算法的复杂性将受限于数组的大小。
我想出了下面的解决方案。除了不使用 aux var (j) 来存储部分结果外,这与您的想法相同。
i = 0
a.each do |item|
p a[i, 4] if(i % 4 == 0)
i +=1
end
关于Ruby每道逻辑题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4103055/