1

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?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Cherenkov
  • 485
  • 1
  • 8
  • 16

2 Answers2

3

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 }
xlembouras
  • 8,215
  • 4
  • 33
  • 42
  • Yep! This works! Basically, because later I need to determine the lenght of each subarray. Thanks! – Cherenkov Oct 10 '15 at 15:43
  • Mr. X, I think you can improve your (good) answer by prepending `sub_array1, sub_array_2 =` and deleting "but" and all that follows. Also, small typo: you forgot the zero. – Cary Swoveland Oct 10 '15 at 16:29
1

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]}
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
davidrac
  • 10,723
  • 3
  • 39
  • 71