Ruby将修改后的数组保存在变量中,而无需更改原始数组

时间:2018-06-21 20:46:09

标签: arrays ruby

我想在数组的值中保存除第一个和最后一个元素之外的值。

例如:

prices = [9, 3, 5, 2, 1]

我需要的元素是:

prices_excl_first = [3, 5, 2, 1]

prices_excl_last = [9, 3, 5, 2]

我想出了几种方法可以从数组中删除元素,包括通过将值的索引传递给slice方法来对值进行切片,如下所示:

first_price = prices.slice(0)
last_price = prices.slice(-1)

然后我们可以将修改后的数组保存到变量中:

array_except_first_price = prices.delete(first_price) #=> [3, 5, 2, 1]
array_except_last_index = prices.delete(last_price) #=> [3, 5, 2]

这有两个问题:

  1. array_except_last_index现在不包含第一个元素
  2. 以后我仍然需要访问完整的原始数组prices

因此,从本质上讲,我该如何在问题中必要时临时修改数组中的元素?

从数组中切片和删除元素会永久影响数组。

5 个答案:

答案 0 :(得分:6)

Ruby有firstlast仅复制第一个和最后一个元素。

询问第一个和最后一个prices.size-1元素。

prices = [9, 3, 5, 2, 1]
except_first = prices.last(prices.size-1)
except_last = prices.first(prices.size-1)

答案 1 :(得分:4)

@Schwern的答案可能是最好的。这是第二好的:

prices = [9, 3, 5, 2, 1]
prices[1..-1] # => [3, 5, 2, 1]
prices[0..-2] # => [9, 3, 5, 2]

drop / take(与您的问题的措词更接近)。

prices.drop(1) # => [3, 5, 2, 1]
prices.take(prices.size-1) # => [9, 3, 5, 2]

答案 2 :(得分:3)

您可以使用each_cons

a, b = prices.each_cons(prices.size - 1).to_a
a #=> [9, 3, 5, 2]
b #=> [3, 5, 2, 1]

答案 3 :(得分:2)

将其展开。

*a, d = prices                                                
c, *b = prices

a #=> [9, 3, 5, 2]
b #=> [3, 5, 2, 1]

答案 4 :(得分:1)

执行破坏性操作之前,可以使用dup复制数组。

prices = [9, 3, 5, 2, 1]

except_first = prices.dup
except_first.delete_at 0

except_last = prices.dup
except_last.delete_at -1

这确实会使阵列重复了几次。如果您要处理大型阵列,则可能是个问题。