Hash.each中的最后一个元素[重复项]

问题描述

|                                                                                                                   这个问题已经在这里有了答案:                                                      

解决方法

例如这样:
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