From: "Guy N. Hurst" Date: 2002-02-26T16:46:55+09:00 Subject: Re: Question with for loop Steve Shreeve wrote: > > I've got a quick question. Sort of a minor issue, but I was wondering about > Ruby's syntax a special situation. I have a bit of code that looks like this: > > b.rpc('ORWU TOOLMENU',[nil]) > b.rpc('ORWU HASKEY',['XUPROGMODE']) > b.rpc('ORQQPX NEW REMINDERS ACTIVE') > ['O RX', 'I RX', 'UD RX', 'IV RX'].each { |val| b.rpc("ORWORDG IEN", [val]) } > b.rpc('ORWU DT', ['NOW']) > b.rpc('ORWCH LOADAL') > > Notice how the third to last line is sort of "doing it's own thing". It would > be nice have all these lines "look the same". Something like this would work: > > b.rpc("ORWORDG IEN", [val]) for val in ['O RX', 'I RX', 'UD RX', 'IV RX'] > How about: b.rpc("ORWORDG IEN",[val||=nil]) while val=(tmp||=['O RX', 'I RX', 'UD RX', 'IV RX']).shift if (tmp=nil).nil? The trailing "if" is only to ensure tmp is nil (to avoid an endless loop), and the "||=" construct is a conditional assignment. This construct can be tested with the following code: irb(main):001:0> def s(t); p t+2; end nil irb(main):002:0> s(val||=nil) while val=(tmp||=[1,2,3]).shift if (tmp=nil).nil? 3 4 5 nil irb(main):003:0> Guy N. Hurst