Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby each logic question

Tags:

arrays

each

ruby

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}

like image 783
Teja Kantamneni Avatar asked Nov 05 '10 02:11

Teja Kantamneni


1 Answers

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
like image 195
Miguel Silva Avatar answered Sep 30 '22 11:09

Miguel Silva