I am trying to solve a simple Ruby problem from Seven Languages in Seven Weeks
Print the contents of an array of sixteen numbers, four numbers at a time, using just
each
Here is what I came up with, can this be done in a simple way or make it better??
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
It can done using each_slice
in one line
a.each_slice(4){|x| p x}
Teja, your solution is ok. As you need to use each, the algorithm complexity is going to be bounded to the size of your array.
I came up with the solution bellow. It is the same idea of yours except that it does not use an aux var (j) to store partial results.
i = 0
a.each do |item|
p a[i, 4] if(i % 4 == 0)
i +=1
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With