且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Ruby类使用静态方法调用私有方法吗?

更新时间:2022-11-23 18:17:45

首先,静态并不是 Ruby行话的真正组成部分。

First off, static is not really part of the Ruby jargon.

让我们举一个简单的例子:

Let's take a simple example:

class Bar
  def self.foo
  end
end

它定义了方法 foo 放在显式对象 self 上,该对象在该范围内返回包含类 Bar
是的,可以将其定义为 class方法,但是 static 在Ruby中实际上没有意义。

It defines the method foo on an explicit object, self, which in that scope returns the containing class Bar. Yes, it can be defined a class method, but static does not really make sense in Ruby.

然后 private 不起作用,因为在显式对象上定义方法(例如 def self.foo

Then private would not work, because defining a method on an explicit object (e.g. def self.foo) bypasses the access qualifiers and makes the method public.

您可以做的是使用 class<<。 self 语法来打开包含类的元类,并将其中的方法定义为实例方法:

What you can do, is to use the class << self syntax to open the metaclass of the containing class, and define the methods there as instance methods:

class Foo
  class << self

    def bar
      do_calc
    end

    def baz
      do_calc
    end

    private

    def do_calc
      puts "calculating..."
    end
  end
end

这将为您提供所需的内容。

This will give you what you need:

Foo.bar
calculating...

Foo.baz
calculating...

Foo.do_calc
NoMethodError: private method `do_calc' called for Foo:Class