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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With