From: Florian Gross Date: 2005-01-08T21:06:26+09:00 Subject: Re: what's the Ruby way to do this? William James wrote: > "If you have never worked with regular expressions before, > they probably look anything but regular". > > How true that is! I am not as familiar with Ruby-style > regular expressions as I would like to be, since I've done > much more programming in Awk, which has less powerful ones. > I see now that I could have made it shorter (and I wouldn't > be surprised if Florian Gross could make it "yet shorter"): > > def snippet(thought) > thought.match(/(\S+(\s+|$)){0,10}/)[0]+($'>""?"...":"") > end Let's try then: def snippet(thought) result = thought.clone result[/^(?:\S*\s+){9}\S*(.+)$/, 1] = "..." ensure return result end def snippet(thought) thought.sub(/^((?:\S*\s+){9}\S*)(.+)$/, '\1...') end But actually I still prefer the solution I gave earlier. Regexps are harder to understand than the equivalent code and gain you little in this case. (Even if you know them, there's still some advanced trickery involved in our pieces of code.)