2011-05-23 176 views
8

可能重複:
Tell the end of a .each loop in ruby最後一個元素

我有一個哈希:

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

和代碼:

foo.each do |elem| 
    # smth 
end 

如何識別循環中的元素是最後一個? 喜歡的東西

if elem == foo.last 
    puts 'this is a last element!' 
end 

回答

15

例如像這樣:

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

的問題,你可能是在地圖項目並不在任何特定的順序來。在我的Ruby版本中,我按照以下順序看到它們:

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

也許您想要遍歷排序的鍵。像這樣,例如:

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 
+3

在Ruby 1.9中,現在已經訂購了哈希。這意味着你可以使用索引來實現某些功能,就像你在這裏所做的那樣,而不需要轉向排序。訂單是插入的順序。 [這](http://www.igvita.com/2009/02/04/ruby-19-internals-ordered-hash/)是一個很好的,簡短的閱讀。對於舊版本的Ruby,這當然不適用。 – simonwh 2011-05-23 11:18:45

+0

我記得像這樣的東西,但不知道在哪個版本中添加了。我還有1.8.7。感謝您的信息和鏈接。 – detunized 2011-05-23 11:25:28