Feature #6240

Enumerable#drop with negative argument

Added by Marc-Andre Lafortune about 2 years ago. Updated over 1 year ago.

[ruby-core:44028]
Status:Assigned
Priority:Normal
Assignee:Yukihiro Matsumoto
Category:core
Target version:next minor

Description

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?

History

#1 Updated by Shugo Maeda about 2 years ago

marcandre (Marc-Andre Lafortune) wrote:

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?

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.

#2 Updated by Marc-Andre Lafortune about 2 years ago

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 toenum :drop, n unless blockgiven?
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.

#3 Updated by Shugo Maeda about 2 years ago

marcandre (Marc-Andre Lafortune) 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:

Ah, I see. It's interesting.

Do you have any use case in mind?

#4 Updated by Yusuke Endoh about 2 years ago

  • Status changed from Open to Assigned
  • Assignee set to Yukihiro Matsumoto

#5 Updated by Yutaka HARA over 1 year ago

  • Target version changed from 2.0.0 to next minor

Also available in: Atom PDF