From: Robert Klemme Date: 2007-09-17T06:20:03+09:00 Subject: Re: Newbie: what's Ruby idiom for word-by-word input? On 16.09.2007 21:08, Alex Shulgin wrote: > Hi, > > What is the Ruby idiom for reading input word-by-word? In other words > -- how to process input while skipping all of the whitespace. > > I would use this code in C++: > > //std::istream& stream; > while (!stream.eof()) > { > std::string str; > stream >> str; > ... > } > > Or something like this in C: > > char str[100]; // please no flame on fixed buffer size :-) > while (!feof(file)) > { > fscanf("%99s", str); > ... > } > > I have tried to use Ruby's scanf("%s") but found it severely broken > (as per my task)--it discards the rest of the input up to the > newline. I currently use the following approach, which I find ugly: > > while not $stdin.eof? do > words = $stdin.gets().scan(/[^\s]+/) > words.each do |w| > ... > end > end > > It takes me to write an inner loop and reads the entire string into > memory and then splits it into array of words... Duh! > > My application is not in any case a time- or memory-critical, nor did > I measured to find the performance bottleneck... however, I desire for > the enlightenment. :-) > > Please show me the Ruby way! > > > Cheers, > Alex > PS: Yes, I've searched the web, tutorials, FAQs, cookbooks, etc. > before posting this. No luck. 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. Kind regards robert