具体效果自己看吧,我没有动文件哦,StringIO.rb可以直接复制到代码里面
附上StringIO.rb(这个文件在Ruby中有两个,一个是Game的一个是1.9的)[code]# encoding: utf-8#--# Copyright (c) 1998-2003 Minero Aoki ## Permission is hereby granted, free of charge, to any person obtaining# a copy of this software and associated documentation files (the# "Software"), to deal in the Software without restriction, including# without limitation the rights to use, copy, modify, merge, publish,# distribute, sublicense, and/or sell copies of the Software, and to# permit persons to whom the Software is furnished to do so, subject to# the following conditions:## The above copyright notice and this permission notice shall be# included in all copies or substantial portions of the Software.## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.## Note: Originally licensed under LGPL v2+. Using MIT license for Rails# with permission of Minero Aoki.#++class StringInput#:nodoc: include Enumerable class @src.size end def each( &block ) stream_check! begin @src.each(&block) ensure @pos = 0 end end def gets stream_check! if idx = @src.index(?\n, @pos) idx += 1 # "\n".size line = @src[ @pos ... idx ] @pos = idx @pos += 1 if @pos == @src.size else line = @src[ @pos .. -1 ] @pos = @src.size + 1 end @lineno += 1 line end def getc stream_check! ch = @src[@pos] @pos += 1 @pos += 1 if @pos == @src.size ch end def read( len = nil ) stream_check! return read_all unless len str = @src[@pos, len] @pos += len @pos += 1 if @pos == @src.size str end alias sysread read def read_all stream_check! return nil if eof? rest = @src[@pos ... @src.size] @pos = @src.size + 1 rest end def stream_check! @closed and raise IOError, 'closed stream' endendclass StringOutput#:nodoc: class