加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby 1.8.7将哈希转换为字符串

发布时间:2020-12-17 04:18:42 所属栏目:百科 来源:网络整理
导读:我没有使用 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
我没有使用 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}"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读