2016-08-05 65 views
2

首先讓我告訴你,我搜索了Google,StackOverflow,甚至像Ruby Cookbook等書籍,但仍無法找到解決這個簡單問題的任何解決方案:在Ruby中使用行計數器打印散列內容

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 

即數字(我稱之爲「行計數器」),必須在每行的開頭。我不知道如何將它添加到迭代中,我該怎麼做?注意:這必須在不使用任何寶石的情況下完成。謝謝。

回答

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| 
+0

沒有大問題,但在插'索引+ 1'? –

+1

或者如果您使用'each.with_index(1)'而不是'each_with_index',那麼您不需要執行插值加法。 –

+0

你好,謝謝你的回答和評論解決了這個問題。但我想知道爲什麼(鍵,值)分組在一起。這個特殊的用法在Ruby教程和書籍中不明顯,或者讓我說我不記得看到這樣的用法。謝謝。 – Romario