Finding Out Current Index in Each Loop (Ruby)

Finding out current index in EACH loop (Ruby)

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

Rails get index of each loop

<% @images.each_with_index do |page, 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

Tell the end of a .each loop in ruby

users.each_with_index do |u, index|
# some code
if index == users.size - 1
# code for the last user
end
end

How do I know what iteration I'm in when using the Integer.times method?

Yes, just have your block accept an argument:

some_value.times{ |index| puts index }
#=> 0
#=> 1
#=> 2
#=> ...

or

some_value.times do |index|
puts index
end
#=> 0
#=> 1
#=> 2
#=> ...

Get the next item in a .each loop without ending the current item's iteration

collection.each_with_index do |item, i|
next_item = collection[i+1] # will be nil when past the end of the collection
end


Related Topics



Leave a reply



Submit