tags:

views:

34

answers:

4

I'm probably trying to be hard headed about this. 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?

+1  A: 

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

Ben
+6  A: 
h.each {|key, (m, n)| puts "#{key} is #{m} and #{n}"}
sepp2k
Yay for destructuring bind!
Jörg W Mittag
+2  A: 
h.each { |key, value| puts "#{key} is #{value.first} and #{value.last}" }
dj2
+1  A: 

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 ')}"}
Telemachus