Ruby 1.8.7 将哈希转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14957162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:45:32  来源:igfitidea点击:

Ruby 1.8.7 convert hash to string

rubyruby-1.8.7

提问by megas

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

我没有使用 ruby​​ 1.8.7,最近我很惊讶:

{: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:

是否准备好使用修复程序将 ruby​​ 1.8.7 的哈希转换为字符串,使其看起来像:

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

回答by Prakash Murthy

hash.to_shas indeed been changed from 1.8.7to 1.9.3.

hash.to_s确实已从 更改1.8.71.9.3

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

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.

通过将哈希转换为 [ key, value ] 对数组,然后使用 Array#join 将该数组转换为字符串并使用默认分隔符,将 hsh 转换为字符串。

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

1.9.3,(参考: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:

您可以在 1.8.7 中对 Hash 类进行猴子补丁,以在本地执行以下操作:

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}"