Report the end of the .each loop in ruby

If I have a loop such as

users.each do |u| #some code end 

Where users is a hash of several users. The easiest conditional logic to see if you are the last user in user hashes and only want to execute specific code for that last user, something like

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

thank

+69
ruby loops ruby-on-rails each
Oct 22 '10 at 20:30
source share
9 answers
 users.each_with_index do |u, index| # some code if index == users.size - 1 # code for the last user end end 
+113
Oct 22 '10 at 20:34
source share

If this is either / or a situation where you apply the code to everyone except the last user, and then some unique code only for the last user, one of the other solutions may be more appropriate.

However, it looks like you are using the same code for all users and some additional code for the last user. If this is the case, it seems more correct and more clearly states your intentions:

 users.each do |u| #code for everyone end users.last.do_stuff() # code for last user 
+35
Oct 22 '10 at 20:39
source share

I think the best approach is:

 users.each do |u| #code for everyone if u.equal?(users.last) #code for the last user end end 
+17
Oct. 25
source share

Have you tried each_with_index ?

 users.each_with_index do |u, i| if users.size-1 == i #code for last items end end 
+8
Oct 22 '10 at 20:35
source share
 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 
+5
Oct 22 2018-10-22
source share

Sometimes it seems to me that it is better to divide the logic into two parts: one for all users and one for the last. So I would do something like this:

 users[0...-1].each do |user| method_for_all_users user end method_for_all_users users.last method_for_last_user users.last 
+3
Apr 30 '14 at 9:07
source share

You can use the @meager approach also for any situation or situation where you apply the code to everyone except the last user, and then a unique code only for the last user.

 users[0..-2].each do |u| #code for everyone except the last one, if the array size is 1 it gets never executed end users.last.do_stuff() # code for last user 

Thus, you do not need a conditional!

+3
Sep 16 '14 at 13:34
source share

There is no last hash method for some versions of ruby

 h = { :a => :aa, :b => :bb } last_key = h.keys.last h.each do |k,v| puts "Put last key #{k} and last value #{v}" if last_key == k end 
0
Jul 23 '13 at 7:06 on
source share

Another solution is to save from StopIteration:

 user_list = users.each begin while true do user = user_list.next user.do_something end rescue StopIteration user.do_something end 
0
Oct 11 '13 at 0:15
source share



All Articles