微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

有没有办法从Ruby中的一个实例调用一个私有的Class方法?

除了self.class.send:方法,args …,当然.我想在类和实例级别做一个相当复杂的方法,而不会重复代码.

更新:

@Jonathan Branam:这是我的假设,但我想确保没有人找到办法. Ruby中的可见性与Java非常不同.你也很正确,私有对类方法不起作用,尽管这将声明一个私有类方法

class Foo
  class <<self
    private
    def bar
      puts 'bar'
    end
  end
end

Foo.bar
# => NoMethodError: private method 'bar' called for Foo:Class

解决方法

这是一个与这个问题一起的代码片段.在类定义中使用“private”不适用于类方法.您需要使用“private_class_method”,如以下示例所示.
class Foo
  def self.private_bar
    # Complex logic goes here
    puts "hi"
  end
  private_class_method :private_bar
  class <<self
    private
    def another_private_bar
      puts "bar"
    end
  end
  public
  def instance_bar
    self.class.private_bar
  end
  def instance_bar2
    self.class.another_private_bar
  end
end

f=Foo.new
f=instance_bar # NoMethodError: private method `private_bar' called for Foo:Class
f=instance_bar2 # NoMethodError: private method `another_private_bar' called for Foo:Class

我没有办法解决这个问题.该文档说您不能指定一个私有方法的接收.此外,您只能从同一实例访问私有方法. Foo类是与Foo的给定实例不同的对象.

不要以我的答案为最终.我当然不是专家,但我想提供一个代码片段,以便其他尝试回答的人将具有适当的私有类方法.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐