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

ruby-on-rails – 哈希不包含’try’方法

发布时间:2020-12-17 01:49:40 所属栏目:百科 来源:网络整理
导读:我注意到 Ruby 1.8.7中的哈希对象与Rails 3.0.10中的哈希对象之间的差异. 例如,在1.8.7 irb中,我得到: 1.8.7 :001 {}.try(:method)NoMethodError: undefned method `try' for {}:Hashfrom (irb):1``` 但是,从3.0.10 rails控制台,我得到: 1.8.7 :003 {}.try
我注意到 Ruby 1.8.7中的哈希对象与Rails 3.0.10中的哈希对象之间的差异.

例如,在1.8.7 irb中,我得到:

1.8.7 :001 > {}.try(:method)
NoMethodError: undefned method `try' for {}:Hash
from (irb):1```

但是,从3.0.10 rails控制台,我得到:

1.8.7 :003 > {}.try(:method_x)
NoMethodError: undefined method `method_x' for {}:Hash
  from (irb):3:in `try'
  from (irb):3

这让我感到惊讶,因为我的印象是在对象中定义了try,它是Hash的祖先,尝试返回nil而不是抛出NoMethodError.

我错过了什么?

解决方法

This surprises me because I was under the impression that try is defined in Object which is an ancestor of Hash and try will return nil instead of throwing a NoMethodError.

What am I missing?

您对定义哪个类尝试的印象是正确的(对象).你缺少的是它定义的文件.它在ActiveSupport库中定义,而不是在Ruby核心库中定义.

所以,你需要

require 'active_support/core_ext/object/try'

第一.

(编辑:李大同)

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

    推荐文章
      热点阅读