Ruby print hash key and value

thisisnotabus picture thisisnotabus · Sep 24, 2013 · Viewed 80.9k times · Source

I'm trying to print key : value Currently I keep getting errors when I try to run my codes.

The code:

output.each do |key, value|
    puts key + ' : ' + value
end

I can not figure out a way to do this on the same line. I've tried various implementations, like using the << symbol. I've also played around with print, using multiple puts statements, and appending both values into a string and printing that.

Answer

Charles Caldwell picture Charles Caldwell · Sep 24, 2013

Depending on the contents of your Hash, you might need to convert the key to a string since it might be a symbol.

puts key.to_s + ' : ' + value

Or, what I would suggest doing, use string interpolation:

puts "#{key}:#{value}"

The reason you are getting an error, if key is indeed not a string, is because it is trying to call the method + on whatever key is. If it does not have a + method, you will get an error.