Afficher un message
Vieux 17/09/2007, 14h47   #5
Robert Klemme
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Newbie: what's Ruby idiom for word-by-word input?

2007/9/17, Alex Shulgin <alex.shulgin@gmail.com>:
> On Sep 17, 12:19 am, Robert Klemme <shortcut...@googlemail.com> 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

  Réponse avec citation
 
Page generated in 0,04939 seconds with 9 queries