簡體   English   中英

Ruby 中的 Array.prototype.splice

[英]Array.prototype.splice in Ruby

一個朋友問我Ruby中實現JavaScript的splice方法效果的最佳和splice方式。 這意味着不對 Array 本身或副本進行迭代。

“從索引開始,刪除長度項目和(可選)插入元素。最后返回數組中刪除的項目。” <<這是誤導,請參閱下面的 JS 示例。

http://www.mennovanslooten.nl/blog/post/41

沒有可選替換的快速 hack:

from_index     = 2
for_elements   = 2
sostitute_with = :test
initial_array  = [:a, :c, :h, :g, :t, :m]
# expected result: [:a, :c, :test, :t, :m]
initial_array[0..from_index-1] + [sostitute_with] + initial_array[from_index + for_elements..-1]

你的是啥呢? 一根線更好。

更新:

// JavaScript
var a = ['a', 'c', 'h', 'g', 't', 'm'];
var b = a.splice(2, 2, 'test'); 
> b is now ["h", "g"]
> a is now ["a", "c", "test", "t", "m"]

我需要生成的“a”數組,而不是“b”。

使用Array#[]=

a = [1, 2, 3, 4, 5, 6]
a[2..4] = [:foo, :bar, :baz, :wibble]
a # => [1, 2, :foo, :bar, :baz, :wibble, 6]

# It also supports start/length instead of a range:
a[0, 3] = [:a, :b]
a # => [:a, :b, :bar, :baz, :wibble, 6]

至於返回已刪除的元素, []=不會這樣做......您可以編寫自己的幫助方法來做到這一點:

class Array
  def splice(start, len, *replace)
    ret = self[start, len]
    self[start, len] = replace
    ret
  end
end

先用slice! 提取要刪除的部分:

a   = [1, 2, 3, 4]
ret = a.slice!(2,2)

這將[1,2]留在a ,將[3,4]留在ret 然后一個簡單的[]=插入新值:

a[2,0] = [:pancakes]

結果是[3,4]ret[1, 2, :pancakes]a 概括:

def splice(a, start, len, replacements = nil)
    r = a.slice!(start, len)
    a[start, 0] = replacements if(replacements)
    r
end

如果您想要可變參數行為,您也可以使用*replacements

def splice(a, start, len, *replacements)
    r = a.slice!(start, len)
    a[start, 0] = replacements if(replacements)
    r
end

暫無
暫無

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

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