Bug #9723

#size does not trigger evaluation of lazy enumerator.

Added by Zeke Fast 11 months ago. Updated 11 months ago.

[ruby-core:61942]
Status:Rejected
Priority:Normal
Assignee:Marc-Andre Lafortune
ruby -v:2.1.1 Backport:2.0.0: UNKNOWN, 2.1: UNKNOWN

Description

Here is the code which shows weird behariour

Steps to reproduce

$ irb
2.1.1 :001 > [1, 2, 3].lazy.select{ |e| e%2 == 1}.size
=> nil
2.1.1 :002 > [1, 2, 3].lazy.select{ |e| e%2 == 1}.to_a
=> [1, 3]
2.1.1 :003 > [1, 2, 3].lazy.size
=> 3

Expected

[1, 2, 3].lazy.select{ |e| e%2 == 1}.size
to return number of elements like [1, 2, 3].lazy.size did.

Actual

[1, 2, 3].lazy.select{ |e| e%2 == 1}.size returns nil.

Environment

Ruby: ruby 2.0.0p457 (2014-03-03) [x86_64-linux-gnu]
RVM: rvm 1.25.22 (stable) by Wayne E. Seguin wayneeseguin@gmail.com, Michal Papis mpapis@gmail.com [[https://rvm.io/]]
OS: Linux xxxxxx 3.13-1-amd64 #1 SMP Debian 3.13.7-1 (2014-03-25) x86_64 GNU/Linux

History

#1 Updated by Marc-Andre Lafortune 11 months ago

  • Status changed from Open to Rejected
  • Assignee set to Marc-Andre Lafortune

The purpose of size is to return the number of elements yielded by an Enumerator without consuming it, i.e. without iterating it.

If enum.size returns an integer, than enum.size == enum.to_a.size must be true.

In your first example, size would have to return 2, which is not possible to do lazily. Use count to do an actual count.

#2 Updated by Zeke Fast 11 months ago

Thank you!

Also available in: Atom PDF