Ruby中的私有/受保护块?

Ruby似乎没有像这样定义受保护/私有块的工具:
protected do
  def method
  end
end

这比较好

protected 

def method 
end 

public

你可能会忘记在受保护的方法后“公开”.

似乎可以使用元编程实现这一点.有什么想法?

解决方法

由于您希望按功能分组,因此可以声明所有方法,然后通过使用受保护的方法声明哪些方法受保护和私有,后跟要保护的方法的符号,以及私有方法相同.

以下课程显示了我的意思.在这个类中,所有方法都是公共的,除了bar_protected和bar_private,它们在结尾处被声明为protected和private.

class Foo

  def bar_public
    print "This is public"
  end

  def bar_protected
    print "This is protected"
  end

  def bar_private
    print "This is private"
  end

  def call_protected
    bar_protected
  end

  def call_private
    bar_private
  end

  protected :bar_protected

  private :bar_private

end

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...