Tell the end of a .each loop in ruby

Splashlin picture Splashlin · Oct 22, 2010 · Viewed 60k times · Source

If i have a loop such as

users.each do |u|
  #some code
end

Where users is a hash of multiple users. What's the easiest conditional logic to see if you are on the last user in the users hash and only want to execute specific code for that last user so something like

users.each do |u|
  #code for everyone
  #conditional code for last user
    #code for the last user
  end
end

Answer

Raphomet picture Raphomet · Oct 22, 2010
users.each_with_index do |u, index|
  # some code
  if index == users.size - 1
    # code for the last user
  end
end