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

在Ruby中覆盖attr_ *方法

发布时间:2020-12-17 01:46:58 所属栏目:百科 来源:网络整理
导读:我正在读这本书“ The Well-Grounded Rubyist”这个随机问题来找我.我知道在Ruby中可以重新打开一个类并覆盖该方法. 例: class A def x "First definition of x" end def x "Second definition of x" endendtest = A.newtest.x #returns "Second definition
我正在读这本书“ The Well-Grounded Rubyist”这个随机问题来找我.我知道在Ruby中可以重新打开一个类并覆盖该方法.

例:

class A
  def x
    "First definition of x"
  end

  def x
    "Second definition of x"
  end
end

test = A.new
test.x #returns "Second definition of x"

根据上面的结果,我很好奇是否可以使用我自己的(随机)定义覆盖类方法attr_accessor.这就是我的想法:

class Dummy
  attr_accessor :test

  def self.attr_accessor(method_name)
    puts "Overwrite the default functionality of attr_accessor by printing this text instead."
  end
end

d = Dummy.new
d.test #not sure why this returns nil instead of putting my message
Dummy.attr_accessor(test) #fails because of ArgumentError: wrong number of arguments (0 for 2..3)

对于上面的两个例子,我希望通过修补并提出问题来更好地理解Ruby以获得洞察力.

解决方法

是的,这是可能的,你刚刚做到了!

d.test #not sure why this returns nil instead of putting my message

返回nil是因为你在下面重新定义它之前使用了attr_accessor:test,因此,Ruby执行了attr_accessor的默认行为并在Dummy类中创建了一个成员和访问器.它返回nil,因为成员的值未设置… nil.

Dummy.attr_accessor(test) #fails because of ArgumentError: wrong number of arguments (0 for 2..3)

不是因为你没想到的原因.此通话有效:

Dummy.attr_accessor("method_name")

问题是您正在调用名为test的方法,而不是提供所有预期值.请参阅Kernel.test()http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-test的文档.

您看到的错误消息是因为您错误地调用了测试方法,而不是因为重新定义attr_accessor时出错.

(编辑:李大同)

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

    推荐文章
      热点阅读