迭代哈希,数组为关键

时间:2011-12-21 20:41:41

标签: ruby

假设我有以下代码:

#!/usr/bin/env ruby -wKU

h = {}
h[[1, "a"]] = "first"
h[[2, "b"]] = "second"

puts h.to_yaml

# case 1 - works fine
h.each do |k, v|
  num, char = k
  puts "key = #{[num, char]}; value = #{v}"
end

# case 2 - works fine
h.each_key do | num, char |
  puts "key = #{[num, char]}; value = #{h[[num, char]]}"
end

# case 3 - Doesn't work
# how can I get all three values in one go?
h.each do | [num, char], v |
  puts "key = #{[num, char]}; value = #{v}"
end

如何创建一个迭代器,我可以在块参数中分配所有3个值(键[0],键[1],值)?这甚至可能吗?

1 个答案:

答案 0 :(得分:5)

h.each do | (num, char), v |
  puts "key = #{[num, char]}; value = #{v}"
end