Skip to content

Instantly share code, notes, and snippets.

@dblack
Created June 28, 2012 16:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dblack/3012525 to your computer and use it in GitHub Desktop.
Save dblack/3012525 to your computer and use it in GitHub Desktop.
Behavior of take_while and drop_while without a block
I'm puzzled by the behavior of take_while and drop_while when called without
a block. They return enumerators -- that part I understand -- but I'm not
understanding how those enumerators behave.
Here's what I mean:
>> enum = [1,2,3,4,5].take_while
=> #<Enumerator: [1, 2, 3, 4, 5]:take_while>
>> enum.next
=> 1
>> enum.next
StopIteration: iteration reached an end
from (irb):3:in `next'
from (irb):3
from /Users/dblack/.rvm/rubies/ruby-1.9.3-p125/bin/irb:16:in `<main>'
>> enum.to_a
=> [1]
drop_while does the same thing. This behavior doesn't seem particularly useful.
Any ideas on why it is this way (up to and including that it's a bug)?
@rue
Copy link

rue commented Jun 28, 2012

[102] pry(main)> [1,2].take_while.to_a
=> [1]
[103] pry(main)>

So, I’d say it considers the no-block return value to be nil or false (which means to stop taking).

@dblack
Copy link
Author

dblack commented Jun 28, 2012

@rue Do you mean the return value of take_while itself? That's an enumerator. Also, it's odd that it iterates once and then stops.

@karthiks
Copy link

enum.count # returns 1

Really weird indeed :={} I'd too love to know the reason for this behavior!

@rue
Copy link

rue commented Jun 28, 2012

@dblack No, my mistake on basically assuming do…while :) This is a bug, I’d say.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment