The method that is used to provide a human-readable representation of an object, is #inspect
. This is also the method used by most REPLs to display objects, although some REPLs use other, REPL-specific methods such as #pretty_inspect
.
It is very important that all of these methods are for human consumption only. You must not parse their output, you must not use them for serialization, processing, or anything other than looking it them for debugging purposes only.
So, knowing that the method in question is Hash#inspect
, you could try overriding the method. Just be very aware that changing the behavior of core methods should never be done in production code. This is an example for this answer only:
module HashPrettyPrintExtension
def inspect
'{ ' <<
map do |k, v|
k = k.to_s if k.is_a?(Symbol)
%Q[#{k.inspect}: #{v.inspect}]
end.join(', ') <<
' }'
end
end
module HashPrettyPrintRefinement
refine Hash do
prepend HashPrettyPrintExtension
end
end
{ "description": "Hello", "id": "H" }
#=> { :description => "Hello", :id => "H" }
using HashPrettyPrintRefinement
{ "description": "Hello", "id": "H" }
#=> { "description": "Hello", "id": "H" }
Note that your proposed output is somewhat restricted. It really only works well for keys which are Symbol
s and values which are String
s, whereas in Ruby, keys can be any arbitrary object and values can be any arbitrary object.
Also, your proposed output is exactly counter to what the goal of #inspect
is, namely provide human-readable debugging output because it is not easily visible that the key is not a string.