使用Ruby

时间:2016-08-05 16:57:44

标签: ruby loops hash

首先让我告诉你,我已经搜索了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

即。一个数字(我称之为"行计数器")必须位于每行的开头。我不知道如何将其添加到迭代中,我该怎么做?注意:必须在不使用任何宝石的情况下完成。感谢。

1 个答案:

答案 0 :(得分:4)

您可以使用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方法只生成块循环的变量;通常是valueindex。因此,您需要明确地解构第一个元素(键和值)。

相比之下,普通数组会将该方法简单地用作

array.each_with_index do |val, index|
相关问题