从数组中删除,并返回在Ruby中删除的元素 [英] Delete from Array and return deleted elements in Ruby
本文介绍了从数组中删除,并返回在Ruby中删除的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何删除从一个数组一些元素,并选择他们?
How can I delete some elements from an array and select them?
例如:
class Foo
def initialize
@a = [1,2,3,4,5,6,7,8,9]
end
def get_a
return @a
end
end
foo = Foo.new
b = foo.get_a.sth{ |e| e < 4 }
p b # => [1,2,3]
p foo.get_a # => [4,5,6,7,8,9,10]
我可以使用 foo.get_a.sth
?
推荐答案
如果您不需要保留的对象ID A
:
If you don't need to retain the object id of a
:
a = [1,2,3,4,5,6,7,8,9,10]
b, a = a.partition{|e| e < 4}
b # => [1, 2, 3]
a # => [4, 5, 6, 7, 8, 9, 10]
如果你确实需要保留的对象ID A
,然后用一个时间数组 C
:
If you do need to retain the object id of a
, then use a temporal array c
:
a = [1,2,3,4,5,6,7,8,9,10]
b, c = a.partition{|e| e < 4}
a.replace(c)
这篇关于从数组中删除,并返回在Ruby中删除的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文