From: Robert Klemme Date: 2007-09-17T22:47:43+09:00 Subject: Re: Newbie: what's Ruby idiom for word-by-word input? 2007/9/17, Alex Shulgin : > On Sep 17, 12:19 am, Robert Klemme wrote: > > > > If you do not need to treat every word before it is read from the input > > you could do this: > > > > $stdin.each do |line| > > line.scan /\w+/ do |word| > > puts word > > end > > end > > > > If your definition of "word" is different (i.e. non whitespace > > characters) you need a different regexp (for example /\S+/). > > > > If you want to read to word boundaries only it becomes more difficult. > > This is more or less the same code as I use, maybe a bit more > readable, tough. :-) > > So there is no way in Ruby to read words w/o reading the whole line of > input and then splitting/scanning the line (which takes us two nested > loops anyway)? Looks very odd to me... Well, you can use #getc and implement the word matching logic yourself. But that is more tedious and it's also questionable whether that will be as efficient. And since a line break is a word boundary anyway the nested loop approach yields the proper result (aka sequence of words) as the other approach. So why bother to create a word iterating solution just to get rid of one level of loop nesting? Kind regards robert