1

Ok, so I have an array:

numbers = ["2", "3", "4", "5"]

and I need to split the array into two arrays with a conditional

numbers.reject!{|x| x > 4 }

and what i need is one array numbers to contain numbers = ["5"] and another array with the rejects rejects = ["2", "3", "4"]

How do I do this? ...It seems so easy with a loop but is there a way to do this in a one liner?

2 Answers 2

6

Check out Enumerable#partition

arr = ["2", "3", "4", "5"]
numbers, rejects = arr.partition{ |x| x.to_i > 4 }
 # numbers = ["5"]
 # rejects = ["2", "3", "4"]
Sign up to request clarification or add additional context in comments.

1 Comment

Nice one-liner. I'm going to submit a more verbose one.
1
numbers = [2, 3, 4, 5]

n_gt_four = numbers.select{|n| n > 4}
n_all_else = numbers - n_gt_four

puts "Original array: " + numbers.join(", ")
puts "Numbers > 4: " + n_gt_four.join(", ")
puts "All else: " + n_all_else.join(", ")

Outputs:

   Original array: 2, 3, 4, 5
   Numbers > 4: 5
   All else: 2, 3, 4

1 Comment

Just because I'm in a silly mood: n_gt_four = numbers.select(&4.method(:<)). ;-)

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.