Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Select and Reject in one method

Is there any built in method that would combine the functions of Enumerable.select (find all which the block equates to true) and Enumerable.reject (find all which the block equates to false)?

Something like

good, bad = list.magic_method { |obj| obj.good? } 
like image 229
Drew Avatar asked Jul 21 '11 15:07

Drew


People also ask

What does .select do in Ruby?

Ruby | Array select() function Array#select() : select() is a Array class method which returns a new array containing all elements of array for which the given block returns a true value. Return: A new array containing all elements of array for which the given block returns a true value.

What does .first mean in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Syntax: range1.first(X) Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.

Does Ruby have a filter method?

The filter() is an inbuilt method in Ruby that returns an array which contains the member value from struct which returns a true value for the given block.

What is reject method in Ruby?

The reject() of enumerable is an inbuilt method in Ruby returns the items in the enumerable which does not satisfies the given condition in the block. It returns an enumerator if no block is given. Syntax: enu.reject { |obj| block }


1 Answers

Looks as if Enumerable.partition is exactly what you are after.

= Enumerable.partition  (from ruby core) ------------------------------------------------------------------------------   enum.partition {| obj | block }  -> [ true_array, false_array ]   enum.partition                   -> an_enumerator  ------------------------------------------------------------------------------  Returns two arrays, the first containing the elements of enum for which the block evaluates to true, the second containing the rest.  If no block is given, an enumerator is returned instead.     (1..6).partition {|i| (i&1).zero?}   #=> [[2, 4, 6], [1, 3, 5]] 

Interesting, I didn't know that was there. ri is an amazing tool...

like image 97
Andy Avatar answered Oct 07 '22 01:10

Andy