From: Robert Klemme Date: 2004-02-01T23:04:51+09:00 Subject: Re: Save the flip/flop op! "Gavin Sinclair" schrieb im Newsbeitrag news:1221728269450.20040201235547@soyabean.com.au... > On Sunday, February 1, 2004, 11:29:50 PM, Robert wrote: > > >> Comments, Phil? Nathaniel? Others? > > > I wouldn't put it into File or IO since this is too specialized > > functionality. It deserves a class of it's own: > > > class FlipFlop > > def initialize(on, off) > > @on, @off = on, off > > @state = false > > end > > > > def ===(o) > > if @state > > @state = false if @off === o > > else > > @state = true if @on === o > > end > > > > @state > > end > > end > > > Nice implementation. Thanks! > The usage is still more verbose than the FF > operator, though. Yeah, but it avoids the speciality of treating ".." and "..." differently when they appear in an if clause. > Perhaps some method to process an enumerable > object? > > # Untested > class FlipFlop > def process(enum) > enum.each do |o| > yield(o) if self === o > end > end > end > > > File.open(path) do |io| > FlipFlop.new(/BEGIN/, /END/).process(io) do |line| > puts line > end > end > > Is that any good? It looks good. The only thing that bothers me a bit is that the iteration is kind of "hidden". In Ruby we typically do enum.each{|elem| do sth. with elem}. It's just a feeling, I can't exactly point to why this might be bad. The only thing that comes to my mind is that you make the whole block dependend on the FF's state while you might want to do something else with the line even if the FF doesn't match. E.g. you could be wanting to do: io.each_line do |line| line.chomp! case line when ff1 # do stuff when ff2 # do other stuff if ff3 === line # nested end end end Dunno whether that is realistic. Regards robert