【问题标题】:How to move first element to the end of array如何将第一个元素移动到数组的末尾
【发布时间】:2013-06-29 10:42:13
【问题描述】:

将数组的第一个元素移动到同一数组的末尾的最佳方法是什么?

即:[a,b,c,d]

“一些操作”

结果:[b,c,d,a]

这个“一些操作”应该是什么?

【问题讨论】:

    标签: ruby arrays


    【解决方案1】:

    Array#rotate

    [a,b,c,d].rotate(1)
    

    【讨论】:

    • Ruby 多么优雅!
    • 或者如果你想将最后一项移动到数组的前面:[a,b,c,d].rotate(-1)
    【解决方案2】:

    是的,可以使用Array#shift

    a = [1,2,7,4]
    a << a.shift
    a # => [2, 7, 4, 1]
    

    【讨论】:

      【解决方案3】:

      正如@sawa 所说,使用rotate。在其他/较旧的语言中,我们会这样做:

      ary.push(ary.shift)
      

      或通过在多个步骤中拆分/切片数组来连接一些东西。

      以上对于数组的左移很有用。换个方向是:

      ary.unshift(ary.pop)
      

      与上述内容一起偶尔有用,用于在二进制级别模拟位旋转。

      【讨论】:

      • 呃,这是数组的左旋转,而不是移位。
      【解决方案4】:
          result=[a,b,c,d]
      #first add first char at last in array
          result << result[0]
      #remove first character from array
          result.shift 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-19
        • 2016-10-10
        相关资源
        最近更新 更多