Real life use of each_cons? (... follow up)

Hi there!

(following up the discussion from last year)

This method actually made my life a lot easier when fitting some data
to a table. I had tens of pictures and wanted to show them in rows -
three columns each.

data.each_cons(3) do |column|
column.each do |picture|
show picture
end
end

I was playing with indices, modulos and stuff. After refactoring with
each_cons, the code looked much cleaner.

cheers!

Hi –

On Mon, 17 May 2010, Jakub wrote:

show picture
end
end

I was playing with indices, modulos and stuff. After refactoring with
each_cons, the code looked much cleaner.

Are you sure you don’t want each_slice rather than each_cons? With
each_cons you’ll get repetition:

array = [1,2,3,4,5,6,7,8,9]
array.each_cons(3) {|c| p c }

 [1, 2, 3]
 [2, 3, 4]
 [3, 4, 5]
 etc.

David


David A. Black, Senior Developer, Cyrus Innovation Inc.

THE Ruby training with Black/Brown/McAnally
COMPLEAT Coming to Chicago area, June 18-19, 2010!
RUBYIST http://www.compleatrubyist.com