class
Importance_2
v1_8_6_287 - Show latest stable - 0 notes - Superclass: Object

Buffered stream.

EXAMPLE 1 — an IO.

  class MyBuf < StreamBuf
    # Do initialize myself before a super class.  Super class might call my
    # method 'read'. (Could be awful for C++ user. :-)
    def initialize(s)
      @s = s
      super()
    end

    # define my own 'read' method.
    # CAUTION: Returning nil means EnfOfStream.
    def read(size)
      @s.read(size)
    end

    # release buffers. in Ruby which has GC, you do not have to call this...
    def terminate
      @s = nil
      super()
    end
  end

  buf = MyBuf.new(STDIN)
  my_str = ''
  p buf[0, 0]               # => '' (null string)
  p buf[0]                  # => 97 (char code of 'a')
  p buf[0, 1]               # => 'a'
  my_str = buf[0, 5]
  p my_str                  # => 'abcde' (5 chars)
  p buf[0, 6]               # => "abcde\n" (6 chars)
  p buf[0, 7]               # => "abcde\n" (6 chars)
  p buf.drop(3)             # => 3 (dropped chars)
  p buf.get(0, 2)           # => 'de' (2 chars)
  p buf.is_eos?             # => false (is not EOS here)
  p buf.drop(5)             # => 3 (dropped chars)
  p buf.is_eos?             # => true (is EOS here)
  p buf[0]                  # => nil (is EOS here)

EXAMPLE 2 — String.

  This is a conceptual example.  No pros with this.

  class StrBuf < StreamBuf
    def initialize(s)
      @str = s
      @idx = 0
      super()
    end

    def read(size)
      str = @str[@idx, size]
      @idx += str.size
      str
    end
  end

Constants

BufSize = 1024 * 8

Attributes

Show files where this class is defined (1 file)
Register or log in to add new notes.