如何使用Ruby向上/向下移动数组元素

时间:2018-05-07 10:24:30

标签: ruby

假设我有这个数组

array = ['a', 'b', 'c', 'd']

什么是定位元素的好方法(例如'b')并使用行中的下一个元素(在本例中为'c')切换它,结果变为:

=> ['a', 'c', 'b', 'd']

4 个答案:

答案 0 :(得分:9)

array[1], array[2] = array[2], array[1]
array #=> ["a", "c", "b", "d"]

array[1, 2] = array.values_at(2, 1)
array #=> ["a", "c", "b", "d"]

答案 1 :(得分:7)

这样做没有功能。您可以像这样交换值:

array = %w[a b c d]
array[1..2] = array[1..2].reverse
array #=> ["a", "c", "b", "d"]

您可以向核心数组类添加一些辅助方法。

class Array
  def move_up(index)
    self[index, 2] = self[index, 2].reverse
    self
  end

  def move_down(index)
    move_up(index - 1)
  end
end

注意:请记住,此解决方案会改变原始数组。您还可以选择创建新阵列的版本。对于此版本,您可以拨打#dupresult = dup),而不是result而不是self

<强>参考文献:

答案 2 :(得分:2)

尝试使用此功能进行交换

array[0],array[1] = array[1],array[0]

或一般

array[i],array[i+1] = array[i+1],array[i]

答案 3 :(得分:2)

假设您希望按索引定位元素,insertdelete_at的组合将起作用:

array = %w[a b c d]
array.insert(2, array.delete_at(1))
array
#=> ["a", "c", "b", "d"]