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

时间:2021-10-27 21:20:43

This question already has an answer here:

这个问题在这里已有答案:

My method:

我的方法:

 def scroll_images
   images_all[1..images_all.length]
 end

I don't like that I'm calling images_all twice, just wondering if there's a good trick to call self or something similar to make this a little cleaner.

我不喜欢我两次调用images_all,只是想知道是否有一个很好的技巧来调用self或类似的东西来使它更清洁。

4 个解决方案

#1


8  

Use -1 instead of the length:

使用-1而不是长度:

 def scroll_images
   images_all[1..-1] # `-1`: the last element, `1..-1`: The second to the last.
 end

Example:

例:

a = [1, 2, 3, 4]
a[1..-1]
# => [2, 3, 4]

#2


11  

You can get the same result in a clearer way using the Array#drop method:

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

a = [1, 2, 3, 4]
a.drop(1)
# => [2, 3, 4]

#3


1  

If you're actually modifying the values of images_all i.e. explicitly drop the first element permanently, just use shift:

如果您实际上正在修改images_all的值,即明确地永久删除第一个元素,只需使用shift:

images_all.shift

#4


1  

Here is one more way using Array#values_at :-

这是使用Array#values_at的另一种方法: -

a = [1, 2, 3, 4]
a.values_at(1..-1) # => [2, 3, 4]

#1


8  

Use -1 instead of the length:

使用-1而不是长度:

 def scroll_images
   images_all[1..-1] # `-1`: the last element, `1..-1`: The second to the last.
 end

Example:

例:

a = [1, 2, 3, 4]
a[1..-1]
# => [2, 3, 4]

#2


11  

You can get the same result in a clearer way using the Array#drop method:

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

a = [1, 2, 3, 4]
a.drop(1)
# => [2, 3, 4]

#3


1  

If you're actually modifying the values of images_all i.e. explicitly drop the first element permanently, just use shift:

如果您实际上正在修改images_all的值,即明确地永久删除第一个元素,只需使用shift:

images_all.shift

#4


1  

Here is one more way using Array#values_at :-

这是使用Array#values_at的另一种方法: -

a = [1, 2, 3, 4]
a.values_at(1..-1) # => [2, 3, 4]