Enumerable#split, any advice on this implementation ?

  • Thread starter Thibaut Barrère
  • Start date
T

Thibaut Barrère

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
 
R

Robert Klemme

Thibaut said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,208
Messages
2,571,082
Members
47,683
Latest member
AustinFairchild

Latest Threads

Top