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
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"
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With