2009-11-13 63 views
1

我可能试图对此进行努力。我试图格式散列键和值的数组输出给用户。 Ruby-doc为我提供了一个值的代码。 http://www.ruby-doc.org/core/classes/Hash.html#M002861将键和多个值分开以便打印。每个

h = { "a" => 100, "b" => 200 } 
h.each {|key, value| puts "#{key} is #{value}" } 

我试图让

h = { "a" => [100,'green'], "b" => [200,'red'] } 
h.each {|key, m,n| puts "#{key} is #{m} and #{n}"} 

produces: 

a is 100 and green 
b is 200 and red 

我有一些运气 h.each {|键,M,N |把 “#{}键为#{[M, 'N']}”

it produces: 

a is 100green 
b is 200red 

我需要我的元素的数组之间的一些空间,我怎么去这样做?

回答

1
h.each {|k,v| puts "#{k} is #{v[0]} and #{v[1]}"} 
7
h.each {|key, (m, n)| puts "#{key} is #{m} and #{n}"} 
+0

耶的解构绑定! – 2009-11-14 00:59:00

3
h.each { |key, value| puts "#{key} is #{value.first} and #{value.last}" } 
2

我的each_pair风扇的哈希值:

h.each_pair {|key, val| puts "#{key} is #{val[0]} and #{val[1]}" } 

或者

h.each_pair {|key, val| puts "#{key} is #{val.join(' and ')}"} 
相关问题