Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the next element in an array but get first if current is last

Tags:

arrays

loops

ruby

I have an array of color codes:

array = %w(#646C74 #F68848 #1FA45C etc...)

Every time I query the array I compare with what color was lastly used and want to get the next one. If the last one used is the last in the array, I want the first one.

Is there a more dedicated or succinct way to solve this than:

index_of_last_used_color = array.index(last_used_color)
next_position = index_of_last_used_color + 1
if color = array[next_position]
    return color
else
    return array.first
end
like image 238
Fellow Stranger Avatar asked Nov 22 '25 09:11

Fellow Stranger


2 Answers

Use cycle method, an enumerator seems what you're looking for.

color_cycle = %w(#646C74 #F68848 #1FA45C).cycle
color_cycle.next # => "#646C74"
color_cycle.next # => "#F68848"
color_cycle.next # => "#1FA45C"
color_cycle.next # => "#646C74"
color_cycle.next # => "#F68848"
like image 188
Ursus Avatar answered Nov 24 '25 01:11

Ursus


Just out of curiosity, there is plain old good arithmetics (modulo calc) still alive:

array = %w(#646C74 #F68848 #1FA45C)
index = 1234
item = array[index % array.size]
like image 28
Aleksei Matiushkin Avatar answered Nov 24 '25 00:11

Aleksei Matiushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!