I need to convert values and keys of a hash to string, in order to correctly prepare it as params for a Net::HTTP.post_form
. For instance:
I need to convert
{:x => [1,2,3,4]}
to
{"x"=>"[1, 2, 3, 4]"}
It's important to convert symbols to string and that arrays are surrounded by quotes.
to_json
returns a string and doesn't solve my problem; I need a hash as return.- the hash may have more keys and values, so I can't hard code
to_s
to each key or value.
How can I perform it?
What about this
Hash[ { :x => [1,2,3,4] }.map { |k, v| [k.to_s, v.to_s] } ]
#=> {"x"=>"[1, 2, 3, 4]"}
Or on Ruby >= 2.1
{ :x => [1,2,3,4] }.map { |k, v| [k.to_s, v.to_s] }.to_h
#=> {"x"=>"[1, 2, 3, 4]"}