我
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是一个定义了内核模块的私有方法,只能在隐式主题上调用它.