From: "Florian G. Pflug" Date: 2003-05-30T21:33:28+09:00 Subject: Re: Iteration - last detection On Fri, May 30, 2003 at 04:14:49AM +0900, Orion Hunter wrote: > Is there any built in functionality for iteration that will allow me to > detect when I am on the last element? This would not be hard for an Array, > using array.length, but what about a Hash? How would I know when I am at > the last element? What about a method each_tuple(tuple_length) in Enumerable, that would be kind of a generalization of each?. This should be O(container.length). module Enumerable def each_tuple(tuple_length) tuple = [nil] * tuple_length each do |element| tuple = tuple[1..-1].push(element) yield(tuple) end (2..tuple_length).each do |i| tuple = tuple[1..-1].push(nil) yield(tuple) end end end s = "" [1,2,3,4,5,6,7,8,9,10].each_tuple(2) do |t| next unless t[0] s << (t[0].to_s + (t[1] ? "," : "")) end puts s #gives "1,2,3,4,5,6,7,8,9,10" [1,2,3,4,5,6,7,8,9,10].each_tuple(2) do |t| puts t.inspect end #gives: #[nil, 1] #[1, 2] #[2, 3] #[3, 4] #[4, 5] #[5, 6] #[6, 7] #[7, 8] #[8, 9] #[9, 10] #[10, nil] greetings, Florian Pflug