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
#   ]
# }

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #ruby.

This post was filed under articles.

Related Posts

Other posts you may be interested in:

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.