我没有使用
ruby 1.8.7,最近我很惊讶:
{:k => 30}.to_s #=> "k30"
有没有准备好使用修复将hash转换为字符串为ruby 1.8.7使它看起来像:
{:k => 30}.to_s #=> "{:k=>30}"
解决方法
hash.to_s确实已从1.8.7更改为1.9.3.
在1.8.7,(参考: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.
在1.9.3,(参考:http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-to_s)
Alias for : inspect
您可以在1.8.7中对Hash类进行猴子修补,以便在本地执行以下操作:
class Hash alias :to_s :inspect end
在修补猴子之前:
1.8.7 :001 > {:k => 30}.to_s => "k30" 1.8.7 :002 > {:k => 30}.inspect => "{:k=>30}"
猴子补丁&后:
1.8.7 :003 > class Hash; alias :to_s :inspect; end => nil 1.8.7 :004 > {:k => 30}.to_s => "{:k=>30}"