'delete_at'和'slice'删除索引处的项目并返回该项目。但我真的不关心被删除的项目。我只想要删除该项目的新数组。 Ruby的Array类似乎没有提供这样的方法。
示例是:
a = ['a','b','c','d']
b = a.remove(2) #b => ['a','b','d']
这里'删除'是一种虚构的方法,可以满足我的需求。我需要原始数组,所以我想要一个新的数组返回。我想知道Ruby是否已经有这样的内置?
答案 0 :(得分:2)
class Array
def remove(idx)
self[0...idx] + self[idx+1..-1]
end
end
答案 1 :(得分:1)
a = ['a','b','c','d']
a.reject {|i| i == a[2] }
#=> ["a", "b", "d"]
答案 2 :(得分:0)
irb(main):001:0> a = %w[ a b c d ]
#=> ["a", "b", "c", "d"]
irb(main):002:0> a.reject.with_index{ |o,i| i==2 }
#=> ["a", "b", "d"]
irb(main):003:0> a
#=> ["a", "b", "c", "d"]
需要Ruby 1.9
进行一些猴子修补:
irb(main):013:0> class Array
irb(main):014:1> def remove_at(i)
irb(main):015:2> self.dup.tap{ |clone| clone.delete_at(i) }
irb(main):016:2> end
irb(main):017:1> end
#=> nil
irb(main):018:0> a.remove_at(2)
#=> ["a", "b", "d"]
irb(main):019:0> a
#=> ["a", "b", "c", "d"]
答案 3 :(得分:0)
它非常hacky:
a = ['a','b','c','d']
b, = [a, a.delete_at(0)] # => ['b','c','d']
但速度更快(在我的eeepc上)
require 'benchmark'
n = 5000
Benchmark.bm do |x|
a = (1..5000).to_a
b = nil
x.report { n.times do; b, = [a, a.delete_at(0)]; end }
a = (1..5000).to_a
b = nil
x.report { n.times do; b = a.reject.with_index{ |o,i| i == 0 }; end }
end
user system total real
0.032000 0.000000 0.032000 ( 0.034002)
21.808000 0.156000 21.964000 ( 22.696298) OMG!