如何在Ruby中删除数组中满足条件的所有元素?

如何在Ruby中删除数组中满足条件的所有元素?,ruby,Ruby,如何在Ruby中实现这一点?有没有一行代码技术? 假设我想去掉整数数组中小于3的所有元素。您可以使用new_array=array.reject{x|x

如何在Ruby中实现这一点?有没有一行代码技术?
假设我想去掉整数数组中小于3的所有元素。

您可以使用
new_array=array.reject{x|x<3}
reject
返回一个新数组)或
array.reject!{| x | x<3}
拒绝!
aka
delete_,如果
在适当位置修改数组)

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

还有一种(更常见的)
select
方法,它的作用类似于
reject
,只是您指定了保留元素的条件,而不是拒绝它们(即,要除去小于3的元素,您可以使用
new|u array=array.select{x | x>=3}

可能值得指出这一点

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

array.delete_如果{| x | x<3}
都一样,但是

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

仍将返回相同的结果,但不会更改“数组”。

这适用于按字母顺序排列的数字和字母。比较它们的值,如果条件改变怎么办

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."]
我们需要删除“Uses”值之后的所有元素 例如:

因此,该设计不起作用(仅删除一个元素):

Ruby的和有点不同<代码>拒绝返回
nil
,并在每次调用块时更改数组。
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."]
array = ["Type", ": Jointed", "Axes", ": 6", "Reach", ": 951 mm", "Capacity", ": 6 Kg"]
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."]