Rails Get Index of "Each" Loop

Rails get index of each loop

<% @images.each_with_index do |page, index| %>

<% end %>

Finding out current index in EACH loop (Ruby)

X.each_with_index do |item, index|
puts "current_index: #{index}"
end

Possible to access the index in a Hash each loop?

If you like to know Index of each iteration you could use .each_with_index

hash.each_with_index { |(key,value),index| ... }

Index is nil in each loop (Ruby)

each does not give you the index. Try with each_with_index

words.each_with_index do |word, index|

Anyway, I'd do this this way

TO_NOT_CAPITALIZE =  %w(and the over)

def titleize(string)
string.split.each_with_index.map do |word, index|
index.zero? || !TO_NOT_CAPITALIZE.include?(word) ? word.capitalize : word
end.join(' ')
end

each_with_index_do starting at 1 for index

I think maybe you misunderstand each_with_index.

each will iterate over elements in an array

[:a, :b, :c].each do |object|
puts object
end

which outputs;

:a
:b
:c

each_with_index iterates over the elements, and also passes in the index (starting from zero)

[:a, :b, :c].each_with_index do |object, index|
puts "#{object} at index #{index}"
end

which outputs

:a at index 0
:b at index 1
:c at index 2

if you want it 1-indexed then just add 1.

[:a, :b, :c].each_with_index do |object, index|
indexplusone = index + 1
puts "#{object} at index #{indexplusone}"
end

which outputs

:a at index 1
:b at index 2
:c at index 3

if you want to iterate over a subset of an array, then just choose the subset, then iterate over it

without_first_element = array[1..-1]

without_first_element.each do |object|
...
end

How can I do a mod and case on the index of an .each do loop in ruby on rails?

Perhaps Enumerable#each_with_index is what you need for this?

http://www.ruby-doc.org/core/classes/Enumerable.html#M001511

contacts.each_with_index do |contact, idx|
quad = idx%4
end

How to loop through an array using .each starting at an index in Ruby

You can also do

array.drop(n).each { |v| puts v }



Related Topics



Leave a reply



Submit