Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby array, get all elements from second to last [duplicate]

Tags:

arrays

ruby

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.

like image 628
neo Avatar asked Jul 18 '14 13:07

neo


2 Answers

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

a = [1, 2, 3, 4]
a.drop(1)
# => [2, 3, 4]
like image 164
toro2k Avatar answered Nov 10 '22 06:11

toro2k


Use -1 instead of the length:

 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]
like image 12
falsetru Avatar answered Nov 10 '22 06:11

falsetru