小编mlo*_*cki的帖子

回应?和受保护的方法

response_to可能不是那么明显吗?在红宝石中工作.考虑一下:


class A

   def public_method
   end

   protected
   def protected_method
   end

   private
   def private_method
   end

end

obj = A.new
obj.respond_to?(:public_method)
# true - that's pretty obvious
obj.respond_to?(:private_method)
# false - as expected
obj.respond_to?(:protected_method)
# true - WTF?
Run Code Online (Sandbox Code Playgroud)

因此,如果'obj'响应protected_method,我们应该期待

obj.protected_method
Run Code Online (Sandbox Code Playgroud)

我不应该提出异常吗?

......但它明显提升了

调用respond_to的文档点?第二个参数设置为true也检查私有方法

obj.respond_to?(:private_method, true)
# true
Run Code Online (Sandbox Code Playgroud)

这更合理

所以问题是如何检查对象是否只响应公共方法?有没有比这更好的解决方案?

obj.methods.include?(:public_method)
# true
obj.methods.include?(:protected_method)
# false
Run Code Online (Sandbox Code Playgroud)

ruby encapsulation access-specifier

15
推荐指数
2
解决办法
6285
查看次数

标签 统计

access-specifier ×1

encapsulation ×1

ruby ×1