tonic tonic - 6 months ago 9
Ruby Question

How to output position of elements in an array

If I have an array:

[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 %>

Answer

You could use the method each_with_index.

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