Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all elements that satisfy a condition in array in Ruby?

Tags:

ruby

How can I implement this in Ruby? Is there any one line of code technique? Let's say I want to get rid of all the elements which are less than 3 of an integer array.

like image 608
Chan Avatar asked Feb 15 '11 16:02

Chan


People also ask

How do you remove an element from an array based on condition?

To remove array element on condition with JavaScript, we can use the array filter method. let ar = [1, 2, 3, 4]; ar = ar.

How do you clean an array from items matching a condition in Ruby?

Remove an Array Element Using the delete_if Method There is also a delete_if method that deletes an element that matches a condition from an array. This also mutates the original array. Note that reject! also modifies arrays in place and can be used similarly as delete_if .

What does .shift do in Ruby?

The shift() is an inbuilt function in Ruby returns the element in the front of the SizedQueue and removes it from the SizedQueue. Parameters: The function does not takes any element.


1 Answers

You can use either new_array = array.reject {|x| x < 3} (reject returns a new array) or array.reject! {|x| x < 3} (reject! aka delete_if modifies the array in place).

There's also the (somewhat more common) select method, which acts like reject except that you specify the condition to keep elements, not to reject them (i.e. to get rid of the elements less than 3, you'd use new_array = array.select {|x| x >= 3}).

like image 92
sepp2k Avatar answered Sep 22 '22 12:09

sepp2k