9

Possible Duplicate:
Tell the end of a .each loop in ruby

I have a Hash:

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

and a code:

foo.each do |elem|
  # smth
end

How to recognize that an element in cycle is last? Something like

if elem == foo.last
  puts 'this is a last element!'
end
Community
  • 1
  • 1
Kir
  • 7,981
  • 12
  • 52
  • 69

1 Answers1

15

For example like this:

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

The problem you might have is that items in a map are not coming in any specific order. On my version of Ruby I see them in the following order:

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

Maybe you want to traverse the sorted keys instead. Like this 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
detunized
  • 15,059
  • 3
  • 48
  • 64
  • 4
    In Ruby 1.9, Hashes are now ordered. This means you can actually use the indexes for something, like you did here, without the need to turn to sorting. The order is the order of insertion. [This](http://www.igvita.com/2009/02/04/ruby-19-internals-ordered-hash/) is a good, short read on this. For older versions of Ruby, this, of course, does not apply. – simonwh May 23 '11 at 11:18
  • I remembered something like this, but wasn't sure in which version this has been added. I have 1.8.7 still. Thanks for the info and the link. – detunized May 23 '11 at 11:25