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.
The each_with_index function in Ruby is used to Iterate over the object with its index and returns value of the given object.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With