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?

5 Answers 5

7

Math to the rescue

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

A link about this modulo operator that we love

Sign up to request clarification or add additional context in comments.

2 Comments

The maths I needed! Thank you!
My pleasure Sir :)
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

Comments

2

You could use rotate:

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

It's 7 because arrays are zero based.

Comments

1

Just out of curiosity using Array#cycle:

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

This is quite inefficient but fancy.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.