Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

syntax

each

ruby

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?

like image 338
Alexander Popov Avatar asked Nov 07 '13 15:11

Alexander Popov


1 Answers

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.

like image 116
sawa Avatar answered Oct 13 '22 17:10

sawa