Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby 1.8.7 convert hash to string

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}"
like image 508
megas Avatar asked Feb 19 '13 12:02

megas


1 Answers

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}" 
like image 81
Prakash Murthy Avatar answered Oct 01 '22 10:10

Prakash Murthy