可能重复:
告诉ruby中.each循环的结束
我有一个哈希:
=> {"foo"=>1, "bar"=>2, "abc"=>3}
Run Code Online (Sandbox Code Playgroud)
和代码:
foo.each do |elem|
# smth
end
Run Code Online (Sandbox Code Playgroud)
如何识别循环中的元素是最后一个?就像是
if elem == foo.last
puts 'this is a last element!'
end
Run Code Online (Sandbox Code Playgroud)
det*_*zed 15
例如这样:
foo.each_with_index do |elem, index|
if index == foo.length - 1
puts 'this is a last element!'
else
# smth
end
end
Run Code Online (Sandbox Code Playgroud)
您可能遇到的问题是地图中的项目没有按任何特定顺序排列.在我的Ruby版本上,我按以下顺序看到它们:
["abc", 3]
["foo", 1]
["bar", 2]
Run Code Online (Sandbox Code Playgroud)
也许你想要遍历排序的键.像这样例如:
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
Run Code Online (Sandbox Code Playgroud)