From: Robert Klemme Date: 2005-02-05T08:35:15+09:00 Subject: Re: iteration the ruby way "Martin DeMello" schrieb im Newsbeitrag news:jZSMd.271421$Xk.130554@pd7tw3no... > David A. Black wrote: >> If your enumerable object has a size method, you can do: >> >> bottom_items.each_with_index do |item,i| >> do_something_with(...) >> unless i == bottom_items.size - 1 >> ... >> end >> end >> >> or something similar with #each_index. > > And if it doesn't, this approach should work: > > irb(main):005:0> b = [1,2,3,4,5] > => [1, 2, 3, 4, 5] > irb(main):006:0> b.inject(lambda {}) {|a,v| a.call; puts v; a = lambda { > puts "- > --" }} > > martin > > p.s. who'd have thunk it Interesting idea to use a proc. I never thought of that. Btw, you don't need the assignment to "a". >> b.inject(lambda {}) {|a,v| a.call; print v; lambda {print " -- "}} 1 -- 2 -- 3 -- 4 -- 5=> # Um... Here's another one - without lambdas: >> b = [1,2,3,4,5] => [1, 2, 3, 4, 5] >> print b.inject{|x,y| print x, " -- ";y}, "\n" 1 -- 2 -- 3 -- 4 -- 5 => nil >> puts b.inject{|x,y| print x, " -- ";y} 1 -- 2 -- 3 -- 4 -- 5 => nil If you really need two different manipulation functions for the first n-1 elements and the last element you can do: puts transform_last( b.inject{|x,y| print transform_first_n(x), " -- ";y} ) There's a nice speciality about inject with no arguments: on the first call the two block args are set to the first and second iteration elements... :-) Kind regards robert