开发者

separating key and multiple values for print with .each

I'm probably trying to be hard headed about t开发者_如何学Chis. I'm trying to format hash key and and array of values for output to user. Ruby-doc give me the code for it for one value. http://www.ruby-doc.org/core/classes/Hash.html#M002861

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

I'm trying to get

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

I've had some luck with h.each{|key,m,n| puts "#{key} is #{[m,'n']} "}

it produces:

a is 100green
b is 200red

I need some space between my array of elements, how do I go about doing that?


h.each {|key, (m, n)| puts "#{key} is #{m} and #{n}"}


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


I'm a fan of each_pair for hashes:

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

Or

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


h.each {|k,v| puts "#{k} is #{v[0]} and #{v[1]}"}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜