Arrays RUBY在循环中删除项
我想删除循环中的一项 我有一个类的实例数组,有时我需要从数组中删除这些项Arrays RUBY在循环中删除项,arrays,ruby,Arrays,Ruby,我想删除循环中的一项 我有一个类的实例数组,有时我需要从数组中删除这些项 class Test attr_reader :to_del def initialize(str) @to_del = str end end tab = Array.new a = Test.new(false) b = Test.new(true) c = Test.new(false) tab.push(a) tab.push(b) tab.push(c) for l
class Test
attr_reader :to_del
def initialize(str)
@to_del = str
end
end
tab = Array.new
a = Test.new(false)
b = Test.new(true)
c = Test.new(false)
tab.push(a)
tab.push(b)
tab.push(c)
for l in tab
if l.to_del == true
l = nil
end
end
p tab
有什么想法吗?用于就地删除:
tab.reject! { |l| l.to_del }
要仅返回已清除的数组,请执行以下操作:
tab.reject &:to_del
整个代码都有php的味道。我同意:
tab = (1..3).map { [true,false].sample }.map { |e| Test.new e }
tab.reject &:to_del
你可以用
看看这个:
tab
#=> [#<Test:0x00000007548768 @to_del=false>, #<Test:0x000000074ea348 @to_del=true>, #<Test:0x000000074b21a0 @to_del=false>]
tab.delete_if {|x| x.to_del}
#=> [#<Test:0x00000007548768 @to_del=false>, #<Test:0x000000074b21a0 @to_del=false>]
选项卡
#=> [#, #, #]
tab.delete_if{x|x.to_del}
#=> [#, #]
还有花式的标签。拒绝!(&:to_del)
快捷方式。@Max不仅是“花哨”Symbol\to_proc
实际上比使用显式块更快。@engineersmnky错了。行为各不相同<代码>Benchmark.bm{x}x.report{n.times{[1,2,3].map{i|i.to_s}};x.report{n.times{[1,2,3].map&:to_s}⇒ <代码>[2.39,2.71]。请不要做出毫无根据的声明。我更喜欢Array.new(3){…}
或3.times.map{…}
到(1..3).映射{…}
,因为索引并不重要。@mudasobwa这不是代码高尔夫<代码>3。时间和数组。新(3)
更具语义。注意,您只需编写选项卡=[Test.new(false)、Test.new(true)、Test.new(false)]
。当您获得使用Ruby的经验时,您会发现for
很少使用。(我从来没有使用过它。)这是因为使用一种枚举接收器元素(这里是数组)的方法几乎总是更好的,到目前为止,这两种答案都是如此。