本文簡要介紹ruby語言中 Array.slice!
的用法。
用法
slice!(n) → object or nil
slice!(start, length) → new_array or nil
slice!(range) → new_array or nil
從 self
移除並返回元素。
當唯一的參數是整數 n
時,刪除並返回 self
中的 nth
元素:
a = [:foo, 'bar', 2]
a.slice!(1) # => "bar"
a # => [:foo, 2]
如果 n
為負數,則從 self
的末尾倒數:
a = [:foo, 'bar', 2]
a.slice!(-1) # => 2
a # => [:foo, "bar"]
如果 n
超出範圍,則返回 nil
。
當唯一的參數是整數 start
和 length
時,從偏移量 start
開始的 self
中刪除 length
元素;在新數組中返回已刪除的對象:
a = [:foo, 'bar', 2]
a.slice!(0, 2) # => [:foo, "bar"]
a # => [2]
如果 start + length
超出數組大小,則刪除並返回從偏移量 start
到末尾的所有元素:
a = [:foo, 'bar', 2]
a.slice!(1, 50) # => ["bar", 2]
a # => [:foo]
如果 start == a.size
和 length
為非負數,則返回一個新的空數組。
如果 length
為負數,則返回 nil
。
當唯一的參數是 Range 對象 range
時,將 range.min
視為上麵的 start
並將 range.size
視為上麵的 length
:
a = [:foo, 'bar', 2]
a.slice!(1..2) # => ["bar", 2]
a # => [:foo]
如果 range.start == a.size
,則返回一個新的空數組。
如果 range.start
大於數組大小,則返回 nil
。
如果range.end
為負數,則從數組末尾倒數:
a = [:foo, 'bar', 2]
a.slice!(0..-2) # => [:foo, "bar"]
a # => [2]
如果 range.start
為負數,則從數組末尾向後計算起始索引:
a = [:foo, 'bar', 2]
a.slice!(-2..2) # => ["bar", 2]
a # => [:foo]
相關用法
- Ruby Array.slice()用法及代碼示例
- Ruby Array.slice用法及代碼示例
- Ruby Array.sort用法及代碼示例
- Ruby Array.shuffle!用法及代碼示例
- Ruby Array.sort_by用法及代碼示例
- Ruby Array.sample()用法及代碼示例
- Ruby Array.select!用法及代碼示例
- Ruby Array.sort_by!用法及代碼示例
- Ruby Array.sort!用法及代碼示例
- Ruby Array.sum用法及代碼示例
- Ruby Array.shift用法及代碼示例
- Ruby Array.sample用法及代碼示例
- Ruby Array.shuffle用法及代碼示例
- Ruby Array.select用法及代碼示例
- Ruby Array.push用法及代碼示例
- Ruby Array.hash用法及代碼示例
- Ruby Array.to_a用法及代碼示例
- Ruby Array.to_h用法及代碼示例
- Ruby Array.to_s用法及代碼示例
- Ruby Array.array + other_array用法及代碼示例
- Ruby Array.take()用法及代碼示例
- Ruby Array.reject!用法及代碼示例
- Ruby Array.flatten!用法及代碼示例
- Ruby Array.reject用法及代碼示例
- Ruby Array.repeated_permutation()用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Array.slice!。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。