Converting a Ruby Hash to a String
I noticed today a couple of visitors to the site who were searching for "ruby convert hash to string" - this article is for them, but also for me in the future when I forget!
One option, would be to use .to_s
which converts anything in Ruby to its internal String representation.
This works if you want to have a representation output to a Ruby for use with copy-pasting into source code:
hash_str = {'key'=> [1,2,3]}
puts hash_str.to_s
# {"key"=>[1, 2, 3]}
hash_sym = {key: [1,2,3]}
puts hash_sym.to_s
# {:key=>[1, 2, 3]}
But this won't quite work for folks that want to have a format that can be used in i.e. other languages or tools. For this, I would recommend pretty-printing it as JSON:
require 'json'
hash_str = {'key'=> [1,2,3]}
puts JSON.pretty_generate(hash_str)
# {
# "key": [
# 1,
# 2,
# 3
# ]
# }
hash_sym = {key: [1,2,3]}
puts JSON.pretty_generate(hash_sym)
# {
# "key": [
# 1,
# 2,
# 3
# ]
# }