Ruby类方法在类方法中调用与否之间是否有区别?
发布时间:2020-12-16 22:56:59 所属栏目:百科 来源:网络整理
导读:我有点好奇地知道,下面两种方法之间有什么区别吗? 使用自我调用类方法 class Test def self.foo puts 'Welcome to ruby' end def self.bar self.foo endend Test.bar#欢迎来到ruby 调用class方法,在class方法中没有self class Test def self.foo puts 'Welc
我有点好奇地知道,下面两种方法之间有什么区别吗?
使用自我调用类方法 class Test def self.foo puts 'Welcome to ruby' end def self.bar self.foo end end Test.bar#欢迎来到ruby class Test def self.foo puts 'Welcome to ruby' end def self.bar foo end end Test.bar#欢迎来到ruby 解决方法
是的,有区别.但不是在你的例子.但是如果foo是一个私有类方法,那么你的第一个版本会引发一个异常,因为你使用一个显式的接收器来调用foo:
class Test def self.foo puts 'Welcome to ruby' end private_class_method :foo def self.bar self.foo end end Test.bar #=> NoMethodError: private method `foo' called for Test:Class 但第二个版本仍然可以工作: class Test def self.foo puts 'Welcome to ruby' end private_class_method :foo def self.bar foo end end Test.bar #=> "Welcome to ruby" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |