tonic tonic - 8 months ago 14
Ruby Question

Outputing position in an array

This is probably a really simple question! If I have an array like the following:

[Red, Blue, Pick, Orange]

The array has been sorted and I'd to show what position they are inside the array.


  1. Red

  2. Blue

  3. Pink

  4. Orange

I'd display the colours to the user like this but cannot work out how to display showing that red is number 1, blue is number 2 and 3 is pink in my sorted list.

<% @colours.each do |colour| %>
<%= colour %>
<% end %>


You could use the method each_with_index:

<% @colours.each_with_index do |colour, i| %>
 <%= "#{i+1}: #{colour}" %>
<% end %>