Ruby:根据块查找条件删除并返回一个数组值

时间:2011-03-29 23:51:17

标签: ruby-on-rails ruby arrays

是否有内置方法从数组中删除值,基于块条件返回true,并返回已删除的值?

这是我正在尝试做的简化版本,但似乎必须有更好的方法:

array = [1,2,3,4,5,6,7,8,9,10]

index = array.index {|v| v == 5} # returns index if block is true

value = array.delete_at(index) # deletes and returns element at index

value则为5

6 个答案:

答案 0 :(得分:22)

您无法更新阵列并返回已删除的另一组值。您可以使用delete_if执行以下操作来删除值并捕获块中逻辑删除的值:

reject = []
 => [] 
content = [1,2,3,4,5,6,7,8,9]
 => [1, 2, 3, 4, 5, 6, 7, 8, 9] 
content.delete_if {|v| reject << v if v > 5}
 => [1, 2, 3, 4, 5] 
reject
 => [6, 7, 8, 9] 
content
 => [1, 2, 3, 4, 5] 

答案 1 :(得分:4)

您真的需要删除原始数组中的项目吗? 你真的只想把它分成两部分 条件?如果是后者,那么:

accepted = [ ]
rejected = [ ]
original.each { |e| (want_this_one(e) ? accepted : rejected).push(e) }

parts = original.inject({ :accepted => [ ], :rejected => [ ] }) do |accumulator, e|
  if(want_this_one(e))
    accumulator[:accepted].push(e)
  else
    accumulator[:rejected].push(e)
  end
  accumulator
end

然后是一个简单的方法包装器,可以很容易地提供一个块:

def categorize(array)
  categories = array.inject({ :accepted => [ ], :rejected => [ ] }) do |accumulator, e|
    if(yield e)
      accumulator[:accepted].push(e)
    else
      accumulator[:rejected].push(e)
    end
    accumulator
  end
  return categories[:accepted], categories[:rejected]
end

kept, deleted = categorize([1, 2, 3, 4, 5]) { |n| n % 2 == 0 }
# kept    = [2, 4]
# deleted = [1, 3, 5]

或者您可以使用Enumerable#partition将数组拆分为两部分。

如果你真的需要就地修改数组,那么这个版本的Wes应该可以解决这个问题:

def slice_out(array)
  dead = [ ]
  array.delete_if do |e|
    if(yield e)
      dead.push(e)
      true
    else
      false  
    end
  end
  dead
end

a = [1,2,3,4]
x = slice_out(a) { |n| n % 2 == 0 }
# a == [1, 3]
# x == [2, 4]

答案 2 :(得分:2)

您可以使用分区。显然,这里的块示例并没有完全合理,但返回已删除的项目并留下。

applicationWillEnterForeground

答案 3 :(得分:2)

Array#extract(Rails 6 +)

如果您使用的是Rails,则从版本6开始,有一种方法Array#extract!,几乎可以满足您的需求。

它将删除并返回该块为其返回真值的元素,并修改原始数组。

请查看以下示例:

array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

values = array.extract! { |value| value == 5 }

# array
# => [1, 2, 3, 4, 6, 7, 8, 9, 10]

# values
# => [5]

答案 4 :(得分:0)

这不适用于每个用例,但是如果您根据某种条件一次从数组中一次提取项目,则可以这样做:

array = [1,2,3,4,5,6,7,8,9,10]
indexed_array = array.index_by { |a| a }  # or whatever your condition is
item = indexed_array.delete(5)
array = indexed_array.values

答案 5 :(得分:-5)

您可以使用values_at例如

>> array = [1,2,3,4,5,6,7,8,9,10]
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>> array.values_at(5)
=> [6]
相关问题