[英]Printing hash contents with a line counter in Ruby
首先,让我告诉您,我已经搜索过Google,StackOverflow甚至是Ruby Cookbook之类的书籍,但仍然找不到这个简单问题的任何解决方案:
myhash = Hash.new 0
myhash["wood"] = "any string"
myhash["palm"] = "any other string"
myhash["pine"] = "any thing"
myhash.each do |key, value|
puts "#{key}: #{value}"
end
我想要这样的输出:
1- wood: any string
2- palm: any other string
3- pine: any thing
也就是说,每行的开头必须有一个数字(我称之为“行计数器”)。 我不知道如何将其添加到迭代中,我该怎么做? 注意:必须在不使用任何宝石的情况下进行。 谢谢。
您可以为此使用each_with_index
。 但是,您需要确定并将键和值指定在带括号的组中。
myhash.each_with_index do |(key, value), index| # <-- Notice the group of (key, val)
puts "#{index} - #{key}: #{value}"
end
之所以需要将括号内的键和值分组,是因为each_with_index
方法只将变量生成到块循环中。 通常是value
和index
。 因此,您需要显式解构第一个元素(键和值)。
相比之下,普通数组将简单地使用该方法作为
array.each_with_index do |val, index|
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.