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

后端 未结 4 1599
我寻月下人不归
我寻月下人不归 2021-02-06 20:51

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.

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-06 21:39

    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."]
    

提交回复
热议问题