【问题标题】:Block inheritance of static function in RubyRuby中静态函数的块继承
【发布时间】:2013-12-20 16:39:49
【问题描述】:

一个小测试用例:

class A
  def self.print
    puts "Hello A"
  end
end


class B < A
end

A.print
B.print

这个输出:

Hello A
Hello A

我想阻止class A 中定义的print 函数的继承。有可能吗?

想要的输出:

Hello A
`<main>': undefined method `print' for B:Class (NoMethodError)

我找到了private_class_method,但这并不是我正在寻找的确切内容,因为它在A.print 调用中失败了。

【问题讨论】:

    标签: ruby oop inheritance


    【解决方案1】:
    class A
      def self.print
        puts "Hello A"
      end
    
      def self.inherited(klass)
        class << klass
          undef :print
        end
      end
    end
    
    class B < A
    end
    
    A.print
    # Hello A
    
    B.print
    # private method `print' called for B:Class (NoMethodError)
    

    【讨论】:

    • 编辑了我的答案。我之前的方法实际上也从A 中删除了该方法。另外,我使用了remove_method,它在子类中不起作用。 undef 但是有效,所以对@Huluk 表示敬意。
    【解决方案2】:
    class B < A
      class << self
        undef print
      end
    end
    

    class &lt;&lt; self 块中声明一个方法与声明它的前缀为self. 相同。 它还允许你想要的行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      • 1970-01-01
      • 2014-06-26
      • 2014-02-25
      相关资源
      最近更新 更多