我认为这里应该是each来自 Enumerable 模块的专门方法。当你实现each方法时,Enumerable 模块会提供很多方便的方法map, drop,诸如此类。
class Directory
include Enumerable
def initialize
# here you should build @objects - a whole list of all objects in
# the current direcory and its subdirectories.
@objects = ....
end
def each
if block_given?
@objects.each { |e| yield(e) }
else
Enumerator.new(self, :each)
end
end
...
end
然后您可以以优雅的方式迭代所有对象:
@directory = Directory.new('start_directory')
@directory.each do |object|
puts object.size # this will prints the sizes for all objects in directory
object.do_some_job # this will call method on object for all your objects
end
这将为目录中的所有对象提供一系列大小
@directory.map { |object| object.size } #=> [435435,64545,23434,45645, ...]
附加示例:
例如,您需要获取包含所有对象的索引和大小的列表
@directory.each_with_index.map { |object, index| [index, object.size] }
#=> [ [0,43543], [1,33534], [2,34543564], [3,345435], ...]