如何重载 ***each*** 来建立所需的顺序
这类似于按顺序重载每个方法中发布的问题,但是区别在于我希望支持所有关联的可枚举方法而无需重新定义。
使用 mixin,如何重写 each 以及由 enumerable 提供的所有关联方法,而不重新定义它们中的每一个。例如:
module Ordering
def self.included base
base.class_eval do
alias_method :old_each,:each
def each *args,&block
reverse.old_each(*args,&block) # sample: just reverse std order
end
end
end
end
class OrderedArray < Array
include Ordering
end
a=OrderedArray.new [1,2,3]
a.each{|_| p _} # works nicely
p a.collect # fails!
生成:
3
2
1
[1, 2, 3]
重新定义 each 似乎没有重新定义 collect!
This is similar to question posted in Overload each method with order but with the difference that I would like to have all associated enumerable methods supported without redefinition.
Using a mixin, how do I override each and all associated methods supplied by enumerable without redefining each of them. For example:
module Ordering
def self.included base
base.class_eval do
alias_method :old_each,:each
def each *args,&block
reverse.old_each(*args,&block) # sample: just reverse std order
end
end
end
end
class OrderedArray < Array
include Ordering
end
a=OrderedArray.new [1,2,3]
a.each{|_| p _} # works nicely
p a.collect # fails!
generates:
3
2
1
[1, 2, 3]
Redefining each doesn't seem to have redefined collect!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您还需要重写比较运算符 (
<=>
) 以使其返回相同的 ordering ,并在您的类中include Enumerable
。You also need to override the comparison operator (
<=>
) to have it return the same ordering , and alsoinclude Enumerable
in your class.