简体   繁体   English

在Ruby中使用行计数器打印哈希内容

[英]Printing hash contents with a line counter in Ruby

first of all let me tell you that I've searched Google, StackOverflow and even books like the Ruby Cookbook, etc. and still I couldn't find any solution for this simple problem: 首先,让我告诉您,我已经搜索过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

I'd like to have an output like this: 我想要这样的输出:

1- wood: any string 
2- palm: any other string 
3- pine: any thing

ie a number (which I call "line counter") must be at the beginning of each line . 也就是说,每行的开头必须有一个数字(我称之为“行计数器”)。 I don't know how to add it into the iteration, how can I do it? 我不知道如何将其添加到迭代中,我该怎么做? Note: That must be done without using any gems. 注意:必须在不使用任何宝石的情况下进行。 Thanks. 谢谢。

You can use each_with_index for this. 您可以为此使用each_with_index However, you need to be sure and designate the key and value into a group with parentheses. 但是,您需要确定并将键和值指定在带括号的组中。

myhash.each_with_index do |(key, value), index|   # <-- Notice the group of (key, val)
  puts "#{index} - #{key}: #{value}"
end

The reason you're required to group the key and value in parentheses is because the each_with_index method takes only produces variables to the block loop; 之所以需要将括号内的键和值分组,是因为each_with_index方法只将变量生成到块循环中。 normally the value and index . 通常是valueindex Therefore, you need to deconstruct the first element (key and value) explicitly. 因此,您需要显式解构第一个元素(键和值)。

For contrast, a normal array would use the method simply as 相比之下,普通数组将简单地使用该方法作为

array.each_with_index do |val, index|

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM