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?

2 Answers 2

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 }
Sign up to request clarification or add additional context in comments.

2 Comments

Yep! This works! Basically, because later I need to determine the lenght of each subarray. Thanks!
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.
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]}

2 Comments

This is lovely.. but I don't think it suits my case.
I believe you can meet the OP's objection by tacking on .values and prepending with arr1, arr2 =.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.