From: E S Date: 2005-01-09T02:55:34+09:00 Subject: Re: what's the Ruby way to do this? > L�hett�j�: Florian Gross > Aihe: 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.) Many things could be considered the 'Ruby Way', but none moreso than messing with the standard library :) class String # snippet / Method # -- Shows the first N words of the String with a continuation. def snippet(words = 10, continuation = '...') ary = self.split[0...words] ary[words - 1] << continuation if ary[words] ary.join(' ') end end p "I just finished reading Dan Simmons' Iliad, it was very good.".snippet # => I just finished reading Dan Simmons' Iliad, it was very... p "I just finished reading Dan Simmons' Iliad, it was very good.".snippet(3) # => I just finished... p "I just finished reading Dan Simmons' Iliad, it was very good.".snippet(10, "...\nRead more...") # => I just finished reading Dan Simmons' Iliad, it was very... Read more... E