モジュール練習

以下で練習として作ったモジュールReadableは、readline, readsome, readallを定義しますが、すべてreadcharに立脚します。readcharはクラスの側で実装されることを期待します。

module Readable
  def readuntil
    s = nil
    while c = readchar
      break if yield(c)
      s ||= ""
      s << c
    end
    s
  end

  def readline
    readuntil {|c| c == ?\n }
  end

  def readsome(n)
    readuntil {|c| (n -= 1) < 0}
  end

  def readall
    readuntil {|c| false}
  end
end

class StringReader
  include Readable

  def initialize(string)
    @string = string
    @index = 0
  end

  def readchar
    c = @string[@index]
    @index += 1 if c
    c
  end
end

a = StringReader.new("Hello\nRubyco\n")
p a.readline                            #=> "Hello"
p a.readline                            #=> "Rubyco"

b = StringReader.new("Hello\nRubyco\n")
p b.readsome(3)                         #=> "Hel"

c = StringReader.new("Hello\nRubyco\n")
p c.readall                             #=> "Hello\nRubyco\n"