Fellow Stranger
Fellow Stranger

Reputation: 34013

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

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

Upvotes: 2

Views: 4315

Answers (3)

the Tin Man
the Tin Man

Reputation: 160551

Looking at the docs for cycle I don't seem to find the possibility to give the enumerator a starting point. I.e. is it possible to get next element without starting from first element each time?

I'd do something like this:

colors = array = %w(646C74 F68848 1FA45C)

"randomly" grab a color from the list:

first_color = colors.delete_at(rand(colors.size))
colors # => ["646C74", "1FA45C"]

and push it onto the end of the list:

colors << first_color

Then you can start cycling after you used the first color:

color_wheel = colors.cycle
colors.size.times do
  puts color_wheel.next
end

# >> 646C74
# >> 1FA45C
# >> F68848

Upvotes: 1

Ursus
Ursus

Reputation: 30056

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"

Upvotes: 10

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

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]

Upvotes: 5

Related Questions