Proxying each method in Ruby
Is this the most efficent way to forward the 'each' call to the Hash's native each method.
Should I ma开发者_高级运维ke @index visible to the outside?
I'm a bit unsure as a block is invovled.
class TimeSlice
def initialize(list)
# @index is a hash
@index = list.do_some_magic()
end
def each(&block)
@index.each(&block)
end
end
@index
should be private. No need to expose it outside the class scope.
Your example is perfectly fine if you only need to delegate the each
method.
For more complex cases you can consider to implement a Delegate design pattern. Ruby comes with a Delegate module.
When it comes to efficiency I dont think there is anything wrong with it. However, you should keep @index
private, otherwise the whole point of the wrapper each
method is lost.
精彩评论