Reputation: 8424
This works in Ruby:
a = 4..Float::INFINITY
p a.take(4) #=> [4,5,6,7]
But I was wondering if it's possible to do something similar where the range would be from negative infinity up to a certain number, say 4, and have a method that will take the last, say 6 elements from that sequence, which would be [-1,0,1,2,3,4].
Upvotes: 1
Views: 73
Reputation: 176382
Getting the last N numbers from a range -infinity..4
is the same of selecting a range of 4..(4-N)
.
4.downto(4-5).to_a
# => [4, 3, 2, 1, 0, -1]
You can package it as a custom method
def lastn(from, n)
from.downto(from-n).to_a
end
Upvotes: 1