From: Robert Klemme Date: 2005-08-29T21:36:22+09:00 Subject: Re: [Q] how to unflatten a flat-array SHIGETOMI, Takuhiko wrote: > greetings, Daniel. true. 'next' works. > >> You can't easily go backwards, but skipping to the next is >> as easy as saying `next'. > > on the other hand, and as your reference 'cannot easyily go > backwards', 'next' forgets current object unless any variable on > outside of the yieldee block. > > how about writing a special yielder like as below .. > > any-enumerable-object.sliding_each do |prev,this,next| > ... > end > > - could be really useful? > - any other good name? Like this? module Enumerable def each_window(size) wind = [] each do |x| wind << x wind.shift if wind.size > size yield *wind if wind.size == size end self end end ?> %w{aa bb cc dd ee ff gg hh ii jj kk}.each_window(3) {|*a| p a} ["aa", "bb", "cc"] ["bb", "cc", "dd"] ["cc", "dd", "ee"] ["dd", "ee", "ff"] ["ee", "ff", "gg"] ["ff", "gg", "hh"] ["gg", "hh", "ii"] ["hh", "ii", "jj"] ["ii", "jj", "kk"] => ["aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh", "ii", "jj", "kk"] >> %w{aa bb cc dd ee ff gg hh ii jj kk}.each_window(3) {|pre,here,post| print pre, ">", here, "<", post, "\n"} aa>bbcc
ddeeffgghhiijj ["aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh", "ii", "jj", "kk"] Kind regards robert