1

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?

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
MikeHolford
  • 1,851
  • 2
  • 21
  • 32

5 Answers5

7

Math to the rescue

list[(8 % list.length) - 1]

A link about this modulo operator that we love

Ursus
  • 29,643
  • 3
  • 33
  • 50
2

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
Jagdeep Singh
  • 4,880
  • 2
  • 17
  • 22
2

You could use rotate:

[5, 8, 10, 11, 15].rotate(7).first
#=> 10

It's 7 because arrays are zero based.

Stefan
  • 109,145
  • 14
  • 143
  • 218
1

Just out of curiosity using Array#cycle:

[5, 8, 10, 11, 15].cycle.take(8).last

This is quite inefficient but fancy.

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
0

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.