Send 允许访问私有变量
考虑下面的代码:
def create_class(class_name, superclass, &block)
klass = Class.new superclass, &block
Object.const_set class_name, klass
end
在我这样做之后:
create_class('User', ActiveRecord::Base)
以下是可以的:
Object.send(:remove_const, :User)
但是这个:
Object.remove_const :User
结果是这样的:
NoMethodError: private method `remove_const' called for Object:Class
? 对我来说没有意义...“发送”可以覆盖 Ruby 的访问检查吗? 请帮忙!
Consider the following code:
def create_class(class_name, superclass, &block)
klass = Class.new superclass, &block
Object.const_set class_name, klass
end
After I do:
create_class('User', ActiveRecord::Base)
the following is ok:
Object.send(:remove_const, :User)
but this:
Object.remove_const :User
results in this:
NoMethodError: private method `remove_const' called for Object:Class
? Does not make sense for me... can 'send' override Ruby's access checks? Please help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来它确实覆盖了 Ruby 的访问检查。
http://joshstaiger.org/archives/2006/12/the_ruby_send_h.html
我的猜测是,您想很好地处理其他人设为私有的内容。 如果您需要使用 send 来调用您未创建的类的方法,您可能应该调用
It looks like it does override Ruby's access checks.
http://joshstaiger.org/archives/2006/12/the_ruby_send_h.html
My guess is that you would like to play nicely with things other people have made private. If you need to use send to call methods of a class you did not create, you should probably call obj.respond_to on it first.