如何从指定索引处的数组中删除元素但不就地执行操作

How do I remove an element from an array at a specified index but not do the operation in-place

Ruby 2.4。我想通过从数组中删除指定索引处的元素来创建一个新数组。我认为 delete_at 是方法,但它就地执行并且不是 return 新创建的数组,而是删除的元素:

2.4.0 :003 > a = ["a", "b", "c"]
 => ["a", "b", "c"]
2.4.0 :004 > a.delete_at(0)
 => "a"
2.4.0 :005 > a
 => ["b", "c"]

如何从指定索引处的数组中删除元素但不执行操作?

您可以复制数组并从此副本中删除元素。使用 tap 到 return 数组,但不是已删除的元素。

2.3.3 :018 > a = ["a", "b", "c"]
 => ["a", "b", "c"] 
2.3.3 :019 > b = a.dup.tap{|i| i.delete_at(0)}
 => ["b", "c"] 
2.3.3 :020 > b
 => ["b", "c"]

另一种方法是使用 rejectwith_index:

2.3.3 :042 > b = a.reject.with_index{|v, i| i == 0 }
 => ["b", "c"] 
2.3.3 :043 > b
 => ["b", "c"]

您希望创建一个新数组,该数组与给定数组相同并减去了给定索引处的元素。

你可以使用 Array#[] (aka Array#slice) and Array#concat.

def copy_wo_element(arr, index_to_exclude)
  arr[0,index_to_exclude].concat(arr[index_to_exclude+1..-1])
end

arr = [1,2,3,4,5]
copy_wo_element(arr, 0)
  #=> [2, 3, 4, 5] 
copy_wo_element(arr, 1)
  #=> [1, 3, 4, 5] 
copy_wo_element(arr, 2)
  #=> [1, 2, 4, 5] 
copy_wo_element(arr, 3)
  #=> [1, 2, 3, 5] 
copy_wo_element(arr, 4)
  #=> [1, 2, 3, 4] 

你可以改写

arr[0,index_to_exclude] + arr[index_to_exclude+1..-1]

但是使用concat避免了创建临时数组arr[index_to_exclude+1..-1]