【问题标题】:Calling a private instance method from a class method in Ruby从 Ruby 中的类方法调用私有实例方法
【发布时间】:2010-09-30 01:35:54
【问题描述】:

我可以创建一个可以被类方法调用的私有实例方法吗?

class Foo
  def initialize(n)
    @n = n
  end
  private # or protected?
  def plus(n)
    @n += n
  end
end

class Foo
  def Foo.bar(my_instance, n)
    my_instance.plus(n)
  end
end

a = Foo.new(5)
a.plus(3) # This should not be allowed, but
Foo.bar(a, 3) # I want to allow this

抱歉,如果这是一个非常基本的问题,但我无法通过 Google 找到解决方案。

【问题讨论】:

  • 你应该解决你的问题,你有一个错字。方法是 bar 还是 plus?
  • 你是对的 - 将修复。谢谢。

标签: ruby oop access-specifier


【解决方案1】:

在 Ruby 中使用 private 或 protected 并没有那么大的作用。您可以在任何对象上调用 send 并使用它拥有的任何方法。

class Foo
  def Foo.bar(my_instance, n)
    my_instance.send(:plus, n)
  end
end

【讨论】:

    【解决方案2】:

    您可以按照 Samuel 的说明进行操作,但它确实绕过了 OO 检查...

    在 Ruby 中,您只能在同一个对象上发送私有方法,并且只对同一个类的对象进行保护。静态方法驻留在元类中,因此它们位于不同的对象(以及不同的类)中 - 因此您无法按照自己的意愿使用私有或受保护。

    【讨论】:

      【解决方案3】:

      你也可以使用instance_eval

      class Foo
        def self.bar(my_instance, n)
          my_instance.instance_eval { plus(n) }
        end
      end
      

      【讨论】:

        猜你喜欢
        • 2010-09-06
        • 2011-02-01
        • 2015-10-26
        • 2012-06-23
        • 1970-01-01
        • 2015-06-26
        • 1970-01-01
        • 1970-01-01
        • 2017-06-11
        相关资源
        最近更新 更多