【问题标题】:What is the easiest way to push an element to the beginning of the array?将元素推送到数组开头的最简单方法是什么?
【发布时间】:2011-08-30 10:35:50
【问题描述】:

我想不出一种单一的方法来做到这一点。有什么办法吗?

【问题讨论】:

    标签: arrays ruby


    【解决方案1】:

    你可以使用insert:

    a = [1,2,3]
    a.insert(0,'x')
    => ['x',1,2,3]
    

    第一个参数是要插入的索引,第二个是值。

    【讨论】:

      【解决方案2】:

      使用unshift 方法怎么样?

      ary.unshift(obj, ...) → ary
      将对象添加到自身前面,向上移动其他元素。

      并在使用中:

      irb>> a = [ 0, 1, 2]
      => [0, 1, 2]
      irb>> a.unshift('x')
      => ["x", 0, 1, 2]
      irb>> a.inspect
      => "["x", 0, 1, 2]"
      

      【讨论】:

      • 我看了,只是没有在快速扫描中看到它们。
      • @Ed:页面顶部的方法列表可以更好地格式化,很难直观地扫描。我找到它是因为我知道我正在寻找的方法名称 :)
      • 如果您无法记住 shiftunshift 之间的哪些添加到数组中,哪些从数组中删除,请在脑海中从名称中删除一个“f”,然后您将得到一个全部- 方向图太清晰。 (然后您必须记住,这些方法不适用于数组的“末端”。;)
      • @Phrogz 多年来我听过的最好的记忆技巧! :-)
      • @Phrogz 直到今天我还在使用那个助记符,把它传给其他人感觉很奇怪。
      【解决方案3】:
      array = ["foo"]
      array.unshift "bar"
      array
      => ["bar", "foo"]
      

      请注意,这是破坏性的!

      【讨论】:

        【解决方案4】:

        你也可以使用array concatenation:

        a = [2, 3]
        [1] + a
        => [1, 2, 3]
        

        这会创建一个新数组并且不会修改原始数组。

        【讨论】:

          【解决方案5】:

          您可以使用methodsolver 来查找Ruby 函数。

          这是一个小脚本,

          require 'methodsolver'
          
          solve { a = [1,2,3]; a.____(0) == [0,1,2,3] }
          

          运行此打印

          Found 1 methods
          - Array#unshift
          

          您可以使用安装methodsolver

          gem install methodsolver
          

          【讨论】:

          • 酷,没想到这样可以写LOL
          • irb> require 'methodsolver' 导致 LoadError: cannot load such file -- method_source 来自 ... 来自 /var/lib/gems/1.9.1/gems/methodsolver-0.0.4/lib/methodsolver.rb:2。红宝石 1.9.3p484,irb 0.9.6,Ubuntu 14。
          • 尝试使用pry 而不是irb
          【解决方案6】:

          自 Ruby 2.5.0 起,Array 附带了 prepend 方法(它只是 unshift 方法的别名)。

          【讨论】:

          • 这也适用于 ruby​​ 2.4.4p296,所以也许只适用于 ruby​​ 2.4?
          【解决方案7】:

          您可以使用prependdelete 的组合,它们既是惯用的又是揭示意图的:

          array.delete(value)  # Remove the value from the array  
          array.prepend(value) # Add the value to the beginning of the array
          

          或者在一行中:

          array.prepend(array.delete(value))
          

          【讨论】:

            猜你喜欢
            • 2016-08-16
            • 2016-09-04
            • 1970-01-01
            • 2019-08-24
            • 1970-01-01
            • 2015-02-23
            • 1970-01-01
            • 2011-08-14
            • 1970-01-01
            相关资源
            最近更新 更多