From: "marcandre (Marc-Andre Lafortune)" Date: 2012-04-02T08:38:31+09:00 Subject: [ruby-core:44047] [ruby-trunk - Feature #6240] Enumerable#drop with negative argument Issue #6240 has been updated by marcandre (Marc-Andre Lafortune). Hi, shugo (Shugo Maeda) wrote: > How Enumerable#drop can know the total number of elements? > The source of elements might be IO. Besides that, the total number of elements might be infinite. `drop` would have to consume the whole iteration, indeed, which is why I was talking about a buffer. The buffer holds elements until we know they are not in the last (-n) elements. Here's a Ruby implementation: class Lazy def drop(n) return to_enum :drop, n unless block_given? if n < 0 buffer = [] each do |e| buffer << e yield buffer.shift if buffer.size > -n end else # ... end end end For infinite sequences, `drop` with negative argument would not be very useful, but it would still yield all elements. ---------------------------------------- Feature #6240: Enumerable#drop with negative argument https://bugs.ruby-lang.org/issues/6240#change-25576 Author: marcandre (Marc-Andre Lafortune) Status: Open Priority: Normal Assignee: Category: core Target version: 2.0.0 Currently, Enumerable#drop works only for non-negative arguments. It could be extended so that negative arguments means dropping from the end: [:hello, :world].drop(-1) # => [:hello] This could especially be interesting for `Lazy#drop`, which would keep a circular buffer of elements before yielding them. (1..6).lazy.drop(-3).each{|x| puts x} # -> prints 1, 2 and 3 Thoughts? -- http://bugs.ruby-lang.org/