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


Ruby Array.insert用法及代碼示例

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

用法

insert(index, *objects) → self

在整數索引 offset 的元素之前或之後插入給定的 objects ;返回 self

index 為非負數時,在偏移量 index 的元素之前插入所有給定的 objects

a = [:foo, 'bar', 2]
a.insert(1, :bat, :bam) # => [:foo, :bat, :bam, "bar", 2]

如果 index 超出數組 (index >= self.size ),則擴展數組:

a = [:foo, 'bar', 2]
a.insert(5, :bat, :bam)
a # => [:foo, "bar", 2, nil, nil, :bat, :bam]

如果沒有給定對象,則什麽都不做:

a = [:foo, 'bar', 2]
a.insert(1)
a.insert(50)
a.insert(-50)
a # => [:foo, "bar", 2]

index 為負數時,插入所有給定的 objects after 偏移量 index+self.size 的元素:

a = [:foo, 'bar', 2]
a.insert(-2, :bat, :bam)
a # => [:foo, "bar", :bat, :bam, 2]

相關用法


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