1, "bar"=>2, "abc"=>3} and...">

Last item in Hash.each

Possible duplicate:
Report the end of the .each loop to ruby

I have a hash:

=> {"foo"=>1, "bar"=>2, "abc"=>3} 

and code:

 foo.each do |elem| # smth end 

How to find out what is the last element in a loop? Something like

 if elem == foo.last puts 'this is a last element!' end 
+8
ruby
source share
1 answer

For example, for example:

 foo.each_with_index do |elem, index| if index == foo.length - 1 puts 'this is a last element!' else # smth end end 

The problem that may arise is that the elements on the map do not arrive in any particular order. In my version of Ruby, I see them in the following order:

 ["abc", 3] ["foo", 1] ["bar", 2] 

Maybe you want to forward sorted keys. For example, for example:

 foo.keys.sort.each_with_index do |key, index| if index == foo.length - 1 puts 'this is a last element!' else p foo[key] end end 
+15
source share

All Articles