In many cases over internet i seen examples of each method for Enumerable as:
def each(&block)
@items.each do |item|
block.call(item)
end
end
Why people not using this one:
def each(&block)
@items.each(&block)
end
Is there any differences?
Actually I think the following version is even more commonly seen:
This is equivalent to your first code sample. There is however a subtle difference between this and your second version:
Observe:
The version that delegates the block to the underlying iterable actually returns an enumerator if no block is given, which is very nice. It allows us to write stuff like this:
To achieve the same with our explicit version, we’d have to adapt it like this:
Which is even more verbose. Bottomline: Delegate the block to an underlying enumerable whenever possible, to save yourself from code duplication and from subtle gotchas like these.
By the way, now that you realize the two-folded nature of your
eachmethod, it would make sense to name it differently. For example, you could follow the example of methods likeString#charsorIO#linesand call your methoditems: