ruby数组,从第二个到最后一个获取所有元素

neo*_*neo 6 ruby arrays

我的方法:

 def scroll_images
   images_all[1..images_all.length]
 end
Run Code Online (Sandbox Code Playgroud)

我不喜欢我打电话images_all两次,只是想知道是否有一个好的技巧可以打电话self或类似的东西,使这个更清洁一点.

tor*_*o2k 12

您可以使用该Array#drop方法以更清晰的方式获得相同的结果:

a = [1, 2, 3, 4]
a.drop(1)
# => [2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

  • 另请参见:[`Array#take`](http://ruby-doc.org/core-2.1.2/Array.html#method-i-take),用于数组的另一侧. (2认同)

fal*_*tru 11

使用-1而不是长度:

 def scroll_images
   images_all[1..-1] # `-1`: the last element, `1..-1`: The second to the last.
 end
Run Code Online (Sandbox Code Playgroud)

例:

a = [1, 2, 3, 4]
a[1..-1]
# => [2, 3, 4]
Run Code Online (Sandbox Code Playgroud)