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

Ruby

Ruby Problem Overview


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.

Ruby Solutions


Solution 1 - Ruby

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}).

Solution 2 - Ruby

Probably worth pointing out that

array.reject! {|x| x < 3}

and

array.delete_if {|x| x < 3}

Are the same, but

array.reject {|x| x < 3}

Will still return the same result, but not change the "array".

Solution 3 - Ruby

  a = [ "a", "b", "c" ]
  a.delete_if {|x| x >= "b" }   #=> ["a"]

Solution 4 - Ruby

This works fine for numbers and letters in alphabetical order. their values are compared, what if the conditions change?

array = ["Type", ": Jointed", "Axes", ": 6", "Reach", ": 951 mm", "Capacity", ": 6 Kg", "Uses", ": ", "Arc welding, material handling, machine loading, application", "This particular unit is in excellent condition with under 700 hours."]

We need to delete all elemetns after the "Uses" value example:

array = ["Type", ": Jointed", "Axes", ": 6", "Reach", ": 951 mm", "Capacity", ": 6 Kg"]

So, that desition is not working (it just remove one element):

array.delete_if {|x| x >= "Uses" }
["Type", ": Jointed", "Axes", ": 6", "Reach", ": 951 mm", "Capacity", ": 6 Kg", ": ", "Arc welding, material handling, machine loading, application", "This particular unit is in excellent condition with under 700 hours."]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChanView Question on Stackoverflow
Solution 1 - Rubysepp2kView Answer on Stackoverflow
Solution 2 - RubyktecView Answer on Stackoverflow
Solution 3 - RubyFernando Diaz GarridoView Answer on Stackoverflow
Solution 4 - RubyAleksei StrizhakView Answer on Stackoverflow