Ruby/File Directory/StringIO

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

Find the fifth byte

require "stringio"
def fifth_byte(file)
  file.seek(5)
  file.read(1)
end
fifth_byte(StringIO.new("123456"))          # => "6"



Performing Random Access on Read-Once Input Streams

require "socket"
require "stringio"
sock = TCPSocket.open("www.example.ru", 80)
sock.write("GET /\n")
file = StringIO.new(sock.read)
file.read(10)                                   # => "<HTML>\r\n<H"
file.rewind
file.read(10)                                   # => "<HTML>\r\n<H"
file.pos = 90
file.read(15)                                   # => " this web page "



Pretending a String is a File

require "stringio"
s = StringIO.new %{I am the very model of a modern major general.
I"ve information vegetable, animal, and mineral.}
 
puts s.pos                                 # => 0
s.each_line { |x| puts x }
puts s.eof?                                # => true
puts s.pos                                 # => 95
puts s.rewind
puts s.pos                                 # => 0
puts s.grep /general/



push data to string

require "stringio"
s = StringIO.new
s << "A string"
s.read
s << ", and more."
s.rewind
s.read                                # => "A string, and more."



Redirecting Standard Input or Output

#!/usr/bin/env ruby
# redirect_stdout.rb
require "stringio"
new_stdout = StringIO.new
$stdout = new_stdout
puts "Hello, hello."
puts "I"m writing to standard output."
$stderr.puts "#{new_stdout.size} bytes written to standard ouput so far."
$stderr.puts "AAA"
$stderr.puts new_stdout.string
$ ruby redirect_stdout.rb



Write to a string

require "stringio"
s = StringIO.new
s.write("Treat it like a file.")
s.rewind
s.write("Act like it"s")
s.string                             # => "Act like it"s a file."



YAML.dump

require "stringio"
require "yaml"
s = StringIO.new
YAML.dump(["A list of", 3, :items], s)
puts s.string