【问题标题】:last element in Hash.each [duplicate]Hash.each 中的最后一个元素 [重复]
【发布时间】:2011-08-31 00:39:17
【问题描述】:

可能重复:
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

【问题讨论】:

    标签: ruby


    【解决方案1】:

    例如这样:

    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
    

    【讨论】:

    • 在 Ruby 1.9 中,哈希现在是有序的。这意味着您实际上可以将索引用于某些事情,就像您在此处所做的那样,而无需转向排序。顺序是插入的顺序。 This 是一个很好的简短读物。对于旧版本的 Ruby,这当然不适用。
    • 我记得类似这样的事情,但不确定这是在哪个版本中添加的。我还有 1.8.7。感谢您提供信息和链接。
    猜你喜欢
    • 2017-04-08
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    相关资源
    最近更新 更多