Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

each_with_index_do starting at 1 for index

I am using a ruby iterator on a view in a rails app like so:

<% ([email protected]).each_with_index do |element, index| %>   ... <% end %> 

I thought the addition of the 1.. instead of just saying: @document.data

would get the trick of having the index above start at 1. But alas, the above code index is still 0 to data.length (-1 effectively). So what am I doing wrong, i need the index to equal 1-data.length...no clue how to set up the iterator to do this.

like image 351
Codejoy Avatar asked Jan 17 '13 20:01

Codejoy


People also ask

What does each_ with_ index do?

The each_with_index function in Ruby is used to Iterate over the object with its index and returns value of the given object.

What does index mean in Ruby?

index is a String class method in Ruby which is used to returns the index of the first occurrence of the given substring or pattern (regexp) in the given string. It specifies the position in the string to begin the search if the second parameter is present. It will return nil if not found.

How do you slice an array in Ruby?

The array. slice() is a method in Ruby that is used to return a sub-array of an array. It does this either by giving the index of the element or by providing the index position and the range of elements to return.


1 Answers

Unless you're using an older Ruby like 1.8 (I think this was added in 1.9 but I'm not sure), you can use each.with_index(1) to get a 1-based enumerator:

In your case it would be like this:

<% @document.data.length.each.with_index(1) do |element, index| %>   ... <% end %> 

Hope that helps!

like image 139
Tyler Rick Avatar answered Oct 06 '22 00:10

Tyler Rick