當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Ruby Array.rotate用法及代碼示例

本文簡要介紹ruby語言中 Array.rotate 的用法。

用法

rotate → new_array
rotate(count) → new_array

返回一個由self 形成的新數組,其中元素從一端旋轉到另一端。

當沒有給出參數時,返回一個類似於 self 的新數組,除了第一個元素已旋轉到最後一個位置:

a = [:foo, 'bar', 2, 'bar']
a1 = a.rotate
a1 # => ["bar", 2, "bar", :foo]

當給定一個非負整數 count 時,返回一個新數組,其中 count 元素從頭到尾旋轉:

a = [:foo, 'bar', 2]
a1 = a.rotate(2)
a1 # => [2, :foo, "bar"]

如果 count 很大,則使用 count % array.size 作為計數:

a = [:foo, 'bar', 2]
a1 = a.rotate(20)
a1 # => [2, :foo, "bar"]

如果 count 為零,則返回 self 的副本,未修改:

a = [:foo, 'bar', 2]
a1 = a.rotate(0)
a1 # => [:foo, "bar", 2]

當給定一個負整數 count 時,從頭到尾沿相反方向旋轉:

a = [:foo, 'bar', 2]
a1 = a.rotate(-2)
a1 # => ["bar", 2, :foo]

如果 count 很小(遠非零),則使用 count % array.size 作為計數:

a = [:foo, 'bar', 2]
a1 = a.rotate(-5)
a1 # => ["bar", 2, :foo]

相關用法


注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Array.rotate。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。