[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Enumerable#split, any advice on this implementation ?

Thibaut Barrère

7/7/2006 9:21:00 AM

Hi

could more advanced rubyists review this code (it's already a mixture
of several things I've seen, but a review cannot hurt!) ?

module Enumerable
def split(pattern)
inject([]) do |memo,obj|
memo.push [] if obj =~ pattern
memo.last << obj
memo
end
end
end

Typical usage: split an array like ['Application starting...','I do
work','Application starting...','I still do work'] into [['Application
starting...','I do work'],['Application starting...','I still do
work']].

(or is there something built-in to handle that?)

thanks!

Thibaut

5 Answers

Robert Klemme

7/7/2006 9:50:00 AM

0

Thibaut Barrère wrote:
> Hi
>
> could more advanced rubyists review this code (it's already a mixture
> of several things I've seen, but a review cannot hurt!) ?
>
> module Enumerable
> def split(pattern)
> inject([]) do |memo,obj|
> memo.push [] if obj =~ pattern
> memo.last << obj
> memo
> end
> end
> end
>
> Typical usage: split an array like ['Application starting...','I do
> work','Application starting...','I still do work'] into [['Application
> starting...','I do work'],['Application starting...','I still do
> work']].
>
> (or is there something built-in to handle that?)

Not that I know of. The name collides with String#split which behaves a
bit differently. And I'd use "pattern === obj" instead of "obj =~
pattern" because that is more generic. Then you can even use a class
object for splitting. Other than that it looks good IMHO.

Kind regards

robert

Trans

7/7/2006 11:53:00 AM

0

#partition (?)

Robert Klemme

7/7/2006 1:59:00 PM

0

Trans wrote:
> #partition (?)

no.

Trans

7/7/2006 7:43:00 PM

0


Robert Klemme wrote:
> Trans wrote:
> > #partition (?)
>
> no.

Ah right. I see. How about #divide_on, or something like that?

T.

Trans

7/8/2006 5:39:00 AM

0


Trans wrote:
> Robert Klemme wrote:
> > Trans wrote:
> > > #partition (?)
> >
> > no.
>
> Ah right. I see. How about #divide_on, or something like that?

Now I recall. It's more akin to to Facets' String#shatter.

T.