【问题标题】:How to get the last element of an array in Ruby?如何在Ruby中获取数组的最后一个元素?
【发布时间】:2012-01-28 05:07:30
【问题描述】:

例子:

a = [1, 3, 4, 5]
b = [2, 3, 1, 5, 6]

如何在不使用a[3]b[4] 的情况下获取数组a 中的最后一个值5 或数组b 中的最后一个值6

【问题讨论】:

    标签: ruby arrays


    【解决方案1】:

    使用-1 索引(负索引从数组末尾倒数):

    a[-1] # => 5
    b[-1] # => 6
    

    Array#last方法:

    a.last # => 5
    b.last # => 6
    

    【讨论】:

    • 我们也不要忘记方便的Array#last :) [1,2,3].last #=> 3
    • @theTinMan 因为 pop 也修改了数组,所以这里不是要求的。
    • 感谢 -ve 标志选项它的强大。
    • 另外,虽然a.last = 10 #=> NoMethodError: undefined method last='a[-1] = 10 按预期工作。
    【解决方案2】:

    另一种方式,使用 splat 运算符:

    *a, last = [1, 3, 4, 5]
    
    STDOUT:
    a: [1, 3, 4]
    last: 5
    

    【讨论】:

      猜你喜欢
      • 2022-06-28
      • 2012-09-27
      • 1970-01-01
      • 2020-07-03
      • 2022-09-29
      • 2012-08-18
      • 1970-01-01
      • 1970-01-01
      • 2017-11-08
      相关资源
      最近更新 更多