Is there any difference between Enumerable # each and Enumerable # each_entry in Ruby?

The enumerated documentation does not explicitly indicate that each is an alias for each_entry , but the description of each_entry exactly matches what I expect from each .

In the examples of both answers, new classes are defined that implement the Enumerable module and define the each method.

Can someone give an example of a built-in class like Array or Hash that behaves differently with each and each_entry ?

+6
source share
2 answers

They are different. Using examples from RDoc:

 class Foo include Enumerable def each yield 1 yield 1, 2 yield end end Foo.new.each_entry{|o| po} # => 1 [1, 2] nil Foo.new.each{|o| po} # => 1 1 nil Foo.new.each{|*o| po} # => [1] [1, 2] [] 

The difference is that each_entry passes all the elements of a single block variable, behaving differently depending on the number of elements passed in one iteration: if not, it takes it as nil , if it is required, a parameter, otherwise it puts them in an array. each , on the other hand, passes to a single block variable only the first object that is passed at each iteration.

+5
source

In addition to @sawa:

 class Alphabet include Enumerable AZ = ('a'..'z') def each AZ.each{|char| yield char} end end p Alphabet.new.each_entry #<Enumerator: #<Alphabet:0x000000028465c8>:each_entry> p Alphabet.new.each #in `block in each': no block given (yield) (LocalJumpError) 
+3
source

Source: https://habr.com/ru/post/957598/


All Articles