1

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 %>
2
  • What about <ol><%= colour %></ol> (assuming this is HTML)? Commented May 4, 2016 at 12:54
  • Red is a constant. What does it equal? Commented May 4, 2016 at 16:00

1 Answer 1

5

You could use the method each_with_index.

<% @colours.each_with_index do |colour, i| %>
 <%= "#{i+1}: #{colour}" %>
<% end %>
Sign up to request clarification or add additional context in comments.

1 Comment

You can also use .each.with_index(1) to have a 1-based index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.