ruby-on-railsrubyloopseach

Tell the end of a .each loop in ruby


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

Solution

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