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

Ruby需要和self.require

发布时间:2020-12-17 02:31:50 所属栏目:百科 来源:网络整理
导读:我 ruby 1.8.7,为什么我可以在main中使用require,但是不能使用self.require? require('date') # okself.require('date') NoMethodError: private method `require' called for main:Objectfrom (irb):22from /usr/lib/ruby/1.8/date.rb:437 众所周知,main是
我 ruby 1.8.7,为什么我可以在main中使用require,但是不能使用self.require?

require('date') # ok
self.require('date') 
NoMethodError: private method `require' called for main:Object
from (irb):22
from /usr/lib/ruby/1.8/date.rb:437

众所周知,main是Object类:
????IRB(主):045:0>自
????=>主要

irb(main):043:0> self.class
=> Object

但我发现它有内核mixin:

irb(main):042:0> self.class.included_modules
=> [Kernel]

而且,我发现require是私有的自我方法:

irb(main):037:0> self.private_methods
=> [... "require",...]

同样的方式,我不能使用self.attr_accessor:

irb(main):051:0> class X
irb(main):052:1> self.attr_accessor(:ssss)
irb(main):053:1> end
NoMethodError: private method `attr_accessor' called for X:Class
from (irb):52
from /usr/lib/ruby/1.8/date.rb:437

它是如何发生的?任何人都可以澄清这些问题吗?

解决方法

检查以下简单示例:

class Person
  def initialize(age)
    @age = age
  end

  def compare_to(other)
    # we're calling a protected method on the other instance of the current class
    age <=> other.age
  end

  # it will not work if we use 'private' here
  protected

  def age
    @age
  end
end

在ruby中我们有隐式和显式方法接收器,检查下一个代码片段:

class Foo
  def a; end

  # call 'a' with explicit 'self' as receiver
  def b; self.a; end

  # call 'a' with implicit 'self' as receiver
  def c; a; end
end

基本上在ruby中如果方法是私有的,它只能在隐式接收器上调用(没有self关键字).在您的示例中,require是一个定义了内核模块的私有方法,只能在隐式主题上调用它.

(编辑:李大同)

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

    推荐文章
      热点阅读