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

时间:2011-02-15 16:12:04

标签: ruby

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

4 个答案:

答案 0 :(得分:58)

您可以使用new_array = array.reject {|x| x < 3}reject返回新数组)或array.reject! {|x| x < 3}reject!又名delete_if修改数组。

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

答案 1 :(得分:13)

可能值得指出

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

array.delete_if {|x| x < 3}

是一样的,但是

array.reject {|x| x < 3}

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

答案 2 :(得分:8)

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

答案 3 :(得分:0)

这适用于按字母顺序排列的数字和字母。比较它们的值,如果条件发生变化会怎么样?

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

我们需要在“使用”值后删除所有elemetns 例如:

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

所以,那个desition没有用(它只删除一个元素):

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