Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

last element in Hash.each [duplicate]

Tags:

ruby

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
like image 921
Kir Avatar asked May 23 '11 09:05

Kir


1 Answers

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
like image 55
detunized Avatar answered Nov 17 '22 15:11

detunized