Tell the end of a .each loop in ruby Tell the end of a .each loop in ruby ruby ruby

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  endend


If it's an either/or situation, where you're applying some code to all but the last user and then some unique code to only the last user, one of the other solutions might be more appropriate.

However, you seem to be running the same code for all users, and some additional code for the last user. If that's the case, this seems more correct, and more clearly states your intent:

users.each do |u|  #code for everyoneendusers.last.do_stuff() # code for last user


I think a best approach is:

users.each do |u|  #code for everyone  if u.equal?(users.last)    #code for the last user  endend