Class: Stream::FilteredStream

Inherits:
WrappedStream show all
Defined in:
lib/stream.rb

Overview

A FilteredStream selects all elements which satisfy a given booelan block of another stream being wrapped.

A FilteredStream is created by the method #filtered:

(1..6).create_stream.filtered { |x| x % 2 == 0 }.to_a ==> [2, 4, 6]

Instance Attribute Summary

Attributes inherited from WrappedStream

#wrapped_stream

Instance Method Summary collapse

Methods inherited from WrappedStream

#unwrapped

Methods included from Stream

#+, #backward, #collect, #concatenate, #concatenate_collected, #create_stream, #current, #current_edge, #each, #empty?, #filtered, #first, #forward, #last, #modify, #move_backward_until, #move_forward_until, #peek, #remove_first, #remove_last, #reverse, #unwrapped

Methods included from Enumerable

#create_stream

Constructor Details

#initialize(other_stream, &filter) ⇒ FilteredStream

Create a new FilteredStream wrapping other_stream and selecting all its elements which satisfy the condition defined by the block_filter_.



348
349
350
351
352
353
# File 'lib/stream.rb', line 348

def initialize(other_stream, &filter)
  super other_stream
  @filter = filter
  @position_holder = IntervalStream.new
  set_to_begin
end

Instance Method Details

#at_beginning?Boolean

Returns:

  • (Boolean)


355
356
357
# File 'lib/stream.rb', line 355

def at_beginning?
  @position_holder.at_beginning?
end

#at_end?Boolean

at_end? has to look ahead if there is an element satisfing the filter

Returns:

  • (Boolean)


360
361
362
363
364
365
366
367
368
369
# File 'lib/stream.rb', line 360

def at_end?
  @position_holder.at_end? and
      begin
        if @peek.nil?
          @peek = wrapped_stream.move_forward_until(&@filter) or return true
          @position_holder.increment_stop
        end
        false
      end
end

#basic_backwardObject



384
385
386
387
388
389
# File 'lib/stream.rb', line 384

def basic_backward
  wrapped_stream.backward unless @peek.nil?
  @peek = nil
  @position_holder.backward
  wrapped_stream.move_backward_until(&@filter) or self
end

#basic_forwardObject



371
372
373
374
375
376
377
378
379
380
381
382
# File 'lib/stream.rb', line 371

def basic_forward
  result =
      if @peek.nil?
        wrapped_stream.move_forward_until(&@filter)
      else
        # Do not move!!
        @peek
      end
  @peek = nil
  @position_holder.forward
  result
end

#posObject

Returns the current position of the stream.



403
404
405
# File 'lib/stream.rb', line 403

def pos
  @position_holder.pos
end

#set_to_beginObject



396
397
398
399
400
# File 'lib/stream.rb', line 396

def set_to_begin
  super
  @peek = nil
  @position_holder.set_to_begin
end

#set_to_endObject



391
392
393
394
# File 'lib/stream.rb', line 391

def set_to_end
  # Not super which is a WrappedStream, but same behavior as in Stream
  basic_forward until at_end?
end