【发布时间】:2011-08-31 00:39:17
【问题描述】:
我有一个哈希:
=> {"foo"=>1, "bar"=>2, "abc"=>3}
还有一个代码:
foo.each do |elem|
# smth
end
如何识别循环中的元素是最后一个? 像
if elem == foo.last
puts 'this is a last element!'
end
【问题讨论】:
标签: 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
例如这样:
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
【讨论】: