Ruby中的私有/受保护块?

前端之家收集整理的这篇文章主要介绍了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
原文链接:https://www.f2er.com/ruby/271203.html

猜你在找的Ruby相关文章