簡體   English   中英

按索引拒絕 Ruby 數組元素的慣用方法

[英]Idiomatic way to reject Ruby array elements by their index

給定一個 Ruby 數組ary1 ,我想生成另一個數組 ary2 ,它具有與ary2相同的元素,但給定的一組ary1索引處的元素ary1

我可以將此功能猴子修補到 Ruby 的Array class 上

class Array
  def reject_at(*indices)
    copy = Array.new(self)
    indices.uniq.sort.reverse_each do |i|
      copy.delete_at i
    end
    return copy
  end
end

然后我可以這樣使用:

ary1 = [:a, :b, :c, :d, :e]
ary2 = ary1.reject_at(2, 4)
puts(ary2.to_s) # [:a, :b, :d]

雖然這很好用,但我覺得我一定遺漏了一些明顯的東西。 Ruby 中是否已經內置了這樣的功能? 例如, Array#slice可以而且應該用於此任務嗎?

不要認為有一個內置的解決方案。 得出以下結論:

ary1 = [:a, :b, :c, :d, :e]
indexes_to_reject = [1,2,3]

ary1.reject.each_with_index{|i, ix| indexes_to_reject.include? ix }

相反,有Array#values_at 您可以通過反轉索引來選擇:

class Array
  def values_without(*indices)
    values_at(*((0...size).to_a - indices))
  end
end

[:a, :b, :c, :d, :e].values_without(2, 4)
# => [:a, :b, :d]

您可以使用reject.with_index

ary1 = [:a, :b, :c, :d, :e]

ary1.reject.with_index { _2.in?([2,4]) }
=> [:a, :b, :d]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM