[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: what's the Ruby way to do this?

e

1/8/2005 5:56:00 PM


> Lähettäjä: Florian Gross <flgr@ccan.de>
> 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, "...\n<a href="/articles/23">Read more...</a>")
# => I just finished reading Dan Simmons' Iliad, it was very...
<a href="/articles/23">Read more...</a>

E