Splitting an Array

  • Thread starter James Edward Gray II
  • Start date
J

James Edward Gray II

I have and Array and I need to iterate over it, finding a subset of the
elements it contains. I want that subset in a new Array and I want the
original Array altered so it no longer contains the subset.

The following code does what I want, but it seems kind of "clunky":

a = [ 1, 2, 3 ]
b = [ ] # so it exists outside the iterator

puts a.delete_if { |e| b << e if e > 1; e > 1; } # prints 1
puts b # prints 2 and 3

Is this the best way to go about it?

Thanks.

James Edward Gray II
 
T

ts

J> I have and Array and I need to iterate over it, finding a subset of the
J> elements it contains. I want that subset in a new Array and I want the
J> original Array altered so it no longer contains the subset.

You can also use Enum#partition

a, b = a.partition { |e| e <= 1}


Guy Decoux
 
A

Austin Ziegler

I have and Array and I need to iterate over it, finding a subset of the
elements it contains. I want that subset in a new Array and I want the
original Array altered so it no longer contains the subset.

The following code does what I want, but it seems kind of "clunky":

a = [ 1, 2, 3 ]
b = [ ] # so it exists outside the iterator

puts a.delete_if { |e| b << e if e > 1; e > 1; } # prints 1
puts b # prints 2 and 3

It's still a bit clunky -- I can't think of a single operation to do
this offhand, but:

b = a.select { |e| e > 1 }
a.delete_if { |e| e > 1 }

-a
 
J

James Edward Gray II

J> I have and Array and I need to iterate over it, finding a subset of
the
J> elements it contains. I want that subset in a new Array and I want
the
J> original Array altered so it no longer contains the subset.

You can also use Enum#partition

a, b = a.partition { |e| e <= 1}

Exactly what I was looking for. Thank you.

James Edward Gray II
 
R

Robert Klemme

James Edward Gray II said:
Exactly what I was looking for. Thank you.

Note, that partition returns two new arrays and leaves the original
unmodified. So for large arrays that might be a problem. That might or
might not be ok, depending on your situation.

Btw, your solution can be written a bit simpler:

a = [1,2,3]
b = []
a.delete_if {|e| e > 1 and b << e}

IMHO that is one of the shortest of the solutions that need only two arrays.

If you know that the array is sorted and that there is at least one element
that will satisfy the condition, more options are possible:

a = [1,2,3]
b = a.slice!(a.each_with_index {|x,i| break i if x > 1} .. -1)

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

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top