Method: MemoryIO::IO#write

Defined in:
lib/memory_io/io.rb

#write(objects, from: nil, as: nil) ⇒ void

This method returns an undefined value.

Write to stream.

Examples:

stream = StringIO.new
io = MemoryIO::IO.new(stream)
io.write('abcd')
stream.string
#=> "abcd"

io.write([1, 2, 3, 4], from: 2, as: :u16)
stream.string
#=> "ab\x01\x00\x02\x00\x03\x00\x04\x00"

io.write(['A', 'BB', 'CCC'], from: 0, as: :c_str)
stream.string
#=> "A\x00BB\x00CCC\x00\x00"
stream = StringIO.new
io = MemoryIO::IO.new(stream)
io.write(%w[123 4567], as: ->(s, str) { s.write(str.size.chr + str) })
stream.string
#=> "\x03123\x044567"
stream = StringIO.new
io = MemoryIO::IO.new(stream)
cpp_string = CPP::String.new('A' * 4, 15, 16)
# equivalent to io.write(cpp_string, as: :'cpp/string')
io.write(cpp_string)
stream.string
#=> "\x10\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00AAAA\x00"

Parameters:

  • objects (Object, Array<Object>)

    Objects to be written.

  • from (Integer) (defaults to: nil)

    The position to start to write.

  • as (nil, Symbol, Proc) (defaults to: nil)

    Decide the method to process writing procedure. See Types for all supported types.

    A Proc is allowed, which should accept stream and one object as arguments.

    If objects is a descendent instance of Types::Type and as is nil, objects.class will be used for as. Otherwise, when as = nil+, this method will simply call stream.write(objects).

See Also:



162
163
164
165
166
167
168
# File 'lib/memory_io/io.rb', line 162

def write(objects, from: nil, as: nil)
  stream.pos = from if from
  as ||= objects.class if objects.class.ancestors.include?(MemoryIO::Types::Type)
  return stream.write(objects) if as.nil?
  conv = to_proc(as, :write)
  Array(objects).map { |o| conv.call(stream, o) }
end