Cherenkov
Cherenkov

Reputation: 495

Divide array into subarray

I want to create two sub-arrays from this array:

 a = [0, 1, 2, 3, 4, 5, 6]

This array will not always contain the same number of elements because it depends on the user input.

For example, in some occasions it'll be:

a = [0, 5]

or:

a = [5, 6, 4]

I want to divide the array into two subarrays. The first one will contain numbers from 1 to 4 (inclusive) and the second one will contain 0, 5 and 6.

In the first example, it will be:

a = [0, 1, 2, 3, 4, 5, 6]
sub_array1 = [1, 2, 3, 4]
sub_array2 = [0, 5, 6]

In the second:

a = [0, 5] 
sub_array1 = []
sub_array2 = [5]

In the third:

a = [5, 6, 4]
sub_array1 = [4]
sub_array2 = [5, 6]

and so on, depending on the user input.

How can I do this?

Upvotes: 1

Views: 126

Answers (2)

xlembouras
xlembouras

Reputation: 8295

First thing that comes to mind is Enumerable#partition.

sub_array1, sub_array2 = [0,1,2,3,4,5,6].partition {|x| (1..4).include? x }
=> [[1,2,3,4], [0,5,6]]

if you have two conditions (I mean if 0,5,6 are an actual condition and not the excluded set) I think that a double iteration wouldn't hurt

a = [0,1,2,3,4,5,6]
sub_array1 = a.select { |x| (1..4).include? x }
sub_array2 = a.select { |x| [0,5,6].include? x }

Upvotes: 3

davidrac
davidrac

Reputation: 10738

You can try something like this:

[0,1,2,3,4,5,6].group_by{|x| [0,5,6].include? x}

The result will be a hash:

{true=>[0, 5, 6], false=>[1, 2, 3, 4]}

In the second case:

[0,5].group_by{|x| [0,5,6].include? x}

The result will be:

{true=>[0, 5]}

Upvotes: 1

Related Questions