views:

72

answers:

4

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

Thanks

+6  A: 
users.each_with_index do |u, index|
  # some code
  if index == users.size - 1
    # code for the last user
  end
end
Raphomet
+2  A: 

Did you tried each_with_index?

users.each_with_index do |u, i|
  if users.size-1 == i
     #code for last items
  end
end
Teja Kantamneni
A: 
h = { :a => :aa, :b => :bb }
h.each_with_index do |(k,v), i|
  puts ' Put last element logic here' if i == h.size - 1
end
DigitalRoss
+9  A: 

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 everyone
end

users.last.do_stuff() # code for last user
meagar
+1 for not needing a conditional, if that's appropriate. (of course, I did here)
Jeremy