簡體   English   中英

怎么辦! 在Ruby中?

[英]How to do take! in Ruby?

采取(保留)數組中前n個元素並刪除其余n個元素的好方法是什么?

如果沒有內置方法,則

def take! ary, n
  ...
end

z = (1..10).to_a
take! z, 5
# z is [1,2,3,4,5]

我只用Array#slice!

x = [1, 2, 3, 4]
x.slice!(2..-1) # Will take! the first 2 elements of the array
x # => [1, 2]

有幾種可能性。

始終有效的瑞士軍刀是Array#replace ,它只是用參數的內容替換了接收者的內容,因此可用於將任何數組轉換為其他數組,因此您可以這樣說:

class Array
  def take!(n)
    replace(take(n))
  end
end

使用Array#slice! 是另一種可能性:

class Array
  def take!(n)
    slice!(0, n)
  end
end

嘗試:

def taker(arr, n)
  arr.pop(arr.length - n)
  arr
end

p taker([1, 2, 3, 4, 5], 2) #=> [1, 2]

使用Array#replace建議自己:

z = (1..10).to_a
z.object_id    # 23576880

def z.take! n
  replace(take n)
end

z.take! 5      # [1, 2, 3, 4, 5]
z.object_id    # 23576880

示例定義了單例方法,但是您可以定義#take! 在您的數組派生類上,對模塊進行優化等。

暫無
暫無

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

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