块和物体
我有一个像这样的对象
class SomeObject
def initialize &block
# do something
end
end
class AnotherObject < SomeObject
def initalize &block
super
# do something with block
end
end
当在AnotherObject
中调用super
时,该块似乎被传递给SomeObject
。这是正确的行为吗?还有什么办法可以避免这种行为吗?
I have an object like this
class SomeObject
def initialize &block
# do something
end
end
class AnotherObject < SomeObject
def initalize &block
super
# do something with block
end
end
When super
is called in AnotherObject
, the block seems to be passed to SomeObject
. Is this the right behaviour and is there away round it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据 rubyspec 这是正确的行为,即使你向 super 传递显式参数(即
super('foo')
)如果你不想传递该块,你可以只传递一个不执行任何操作的块,尽管这并不完全是同样的事情(例如,如果方法根据
block_given?
更改其行为? )这似乎
是一种完全不向 super 传递任何块的方法,尽管我在 ruby 规范中找不到这种方法。
According to rubyspec this is the correct behaviour, even if you pass explicit arguments to super (i.e.
super('foo')
)If you don't want to pass that block, you could just pass a block that does nothing, although this isn't quite the same thing (e.g. if the method changes its behaviour based on
block_given?
)It appears that
is a way to pass no block at all to super, although I couldn't find this in ruby spec.