2009-11-13 70 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 ')}"} 
相關問題