Ruby 1.8.7 convert hash to string

megas picture megas · Feb 19, 2013 · Viewed 40.3k times · Source

I wasn't working with ruby 1.8.7 and recently I was surprised that:

{:k => 30}.to_s #=> "k30"

Is there ready to use fix to convert hash to string for ruby 1.8.7 to make it look like:

{:k => 30}.to_s #=> "{:k=>30}"

Answer

Prakash Murthy picture Prakash Murthy · Feb 19, 2013

hash.to_s has indeed been changed from 1.8.7 to 1.9.3.

In 1.8.7, (ref: http://ruby-doc.org/core-1.8.7/Hash.html#method-i-to_s):

Converts hsh to a string by converting the hash to an array of [ key, value ] pairs and then converting that array to a string using Array#join with the default separator.

In 1.9.3, (ref: http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-to_s)

Alias for : inspect

You could monkey-patch Hash class in 1.8.7 to do the same locally with the following:

class Hash
  alias :to_s :inspect
end

Before monkey-patching:

1.8.7 :001 > {:k => 30}.to_s
 => "k30" 
1.8.7 :002 > {:k => 30}.inspect
 => "{:k=>30}"

Monkey-patching & after:

1.8.7 :003 > class Hash; alias :to_s :inspect; end
 => nil 
1.8.7 :004 > {:k => 30}.to_s
 => "{:k=>30}"