Class: Hikkmemo::RingBuffer
- Inherits:
-
Object
- Object
- Hikkmemo::RingBuffer
- Defined in:
- lib/hikkmemo/ring_buffer.rb
Instance Method Summary collapse
-
#initialize(capacity) ⇒ RingBuffer
constructor
A new instance of RingBuffer.
- #last_n(n) ⇒ Object
- #pop ⇒ Object
- #push(elem) ⇒ Object
Constructor Details
#initialize(capacity) ⇒ RingBuffer
Returns a new instance of RingBuffer.
3 4 5 6 |
# File 'lib/hikkmemo/ring_buffer.rb', line 3 def initialize(capacity) @buff = [nil] * capacity @i = 0 end |
Instance Method Details
#last_n(n) ⇒ Object
19 20 21 22 23 |
# File 'lib/hikkmemo/ring_buffer.rb', line 19 def last_n(n) n = [n, @buff.size].min i = @i == 0 ? @buff.size : @i i < n ? @buff[-(n-i)..-1] + @buff[0..i-1] : @buff[i-n..i-1] end |
#pop ⇒ Object
14 15 16 17 |
# File 'lib/hikkmemo/ring_buffer.rb', line 14 def pop @i = (@i == 0 ? @buff.size : @i) - 1 @buff[@i] end |
#push(elem) ⇒ Object
8 9 10 11 12 |
# File 'lib/hikkmemo/ring_buffer.rb', line 8 def push(elem) @buff[@i] = elem @i = @i == @buff.size - 1 ? 0 : @i + 1 self end |