ruby-on-rails – Ruby:基于块查找条件删除并返回数组值

根据块条件返回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

值为5

您无法更新阵列,并返回一组不同的值,这些值将被删除.您可以使用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] 
http://stackoverflow.com/questions/5480329/ruby-delete-and-return-an-array-value-based-on-block-find-condition

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:ruby-on-rails – Ruby:基于块查找条件删除并返回数组值