Reputation: 1931
I've had a tough time finding an exact example of this.
If I have an array that contains 5 elements. E.g.
list = [5, 8, 10, 11, 15]
I would like to fetch what would be the 8th (for example) element of that array if it were to be looped. I don't want to just duplicate the array and fetch the 8th element because the nth
element may change
Essentially the 8th element should be the number 10.
Any clean way to do this?
Upvotes: 1
Views: 219
Reputation: 114138
You could use rotate
:
[5, 8, 10, 11, 15].rotate(7).first
#=> 10
It's 7
because arrays are zero based.
Upvotes: 2
Reputation: 1163
I ran these in my irb to get the output,
irb(main):006:0> list = [5, 8, 10, 11, 15]
=> [5, 8, 10, 11, 15]
irb(main):007:0> list[(8 % list.length) - 1]
=> 10
hope it will help you.
Upvotes: 0
Reputation: 121000
Just out of curiosity using Array#cycle
:
[5, 8, 10, 11, 15].cycle.take(8).last
This is quite inefficient but fancy.
Upvotes: 1
Reputation: 30056
Math to the rescue
list[(8 % list.length) - 1]
A link about this modulo operator that we love
Upvotes: 7
Reputation: 4920
This should do:
def fetch_cycled_at_position(ary, num)
ary[(num % ary.length) - 1]
end
ary = _
=> [5, 8, 10, 11, 15]
fetch_cycled_at_position(ary, 1) # Fetch first element
=> 5
fetch_cycled_at_position(ary, 5) # Fetch 5th element
=> 15
fetch_cycled_at_position(ary, 8) # Fetch 8th element
=> 10
Upvotes: 2