Think I need an Array#split

  • Thread starter Bertram Scharpf
  • Start date
B

Bertram Scharpf

Hi,

wouldn't it be a good idea to have a method doing this:

['a','b','','c','d','','e'].split ''
#=> [['a','b'],['c','d'],['e']]

I wrote this method for my program in Ruby, but if you were
interested in integrating it into the language, I would
like to contribute it to `array.c'.

I made both solutions available at
<http://projects.bertram-scharpf.de/tmp/arraysplit.tar.gz>.

Bertram


P.S.: For those who look at the C code: is it OK not to
destroy the last `cur' object?
 
L

leon breedt

I had a look, perhaps it could emulate String#split by performing an
"awk split" (on whitespace) if there is no delimiter argument given?
Also, allowing a Regexp as a
delimiter would further emulate the String#split functionality.
P.S.: For those who look at the C code: is it OK not to
destroy the last `cur' object?
Its fine, Ruby uses a mark-and-sweep GC, so unless you've explicitly
marked 'cur' yourself (pushing it onto another array will cause it to
get marked automatically), it will get destroyed at the next GC run.

Regards
Leon
 
R

Robert Klemme

leon breedt said:
I had a look, perhaps it could emulate String#split by performing an
"awk split" (on whitespace) if there is no delimiter argument given?
Also, allowing a Regexp as a
delimiter would further emulate the String#split functionality.

Another option would be an optional block that evaluates to true for
delimiters. I didn't look at the proposed implementation, but here's how
I'd do it:

module Enumerable
def split(delim = /\A\s*\z/, &b)
b ||= lambda {|x| delim === x}
inject([[]]) do |ar, x|
if b.call x
ar << []
else
ar[-1] << x
end
ar
end
end
end

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
473,755
Messages
2,569,539
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top