The Enumerable documentation does not state explicitly that each
is an alias for each_entry
, but the description of each_entry
matches exactly what I would expect from each
.
In the examples of both answers new classes are defined, which implement the Enumerable
module and define the each
method.
Can someone give an example of a built-in class, like Array
or Hash
, which behaves differently with each
and each_entry
?
They are different. Using the examples from RDoc:
class Foo
include Enumerable
def each
yield 1
yield 1, 2
yield
end
end
Foo.new.each_entry{|o| p o}
# =>
1
[1, 2]
nil
Foo.new.each{|o| p o}
# =>
1
1
nil
Foo.new.each{|*o| p o}
# =>
[1]
[1, 2]
[]
The difference is that each_entry
passes all elements to the sole block variable by behaving differently depending on the number of elements passed in a single iteration: if none, it takes it as nil
, if one, it takes that parameter, otherwise, it puts them in an array. each
, on the other hand, passes to the sole block variable only the first object that is passed in each iteration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With