instance method
StringIO#each_byte
() { (::Integer arg0) -> untyped } -> self
() -> ::Enumerator[::Integer, self]
each_byte {|byte| ... } → self
ext/stringio/stringio.c
View on GitHub ↗
static VALUE
strio_each_byte(VALUE self)
{
struct StringIO *ptr;
RETURN_ENUMERATOR(self, 0, 0);
while ((ptr = strio_to_read(self)) != NULL) {
char c = RSTRING_PTR(ptr->string)[ptr->pos++];
rb_yield(CHR2FIX(c));
}
return self;
}
With a block given, calls the block with each remaining byte in the stream; positions the stream at end-of-file; returns self:
Example
bytes = [] strio = StringIO.new('hello') # Five 1-byte characters. strio.each_byte {|byte| bytes.push(byte) } strio.eof? # => true bytes # => [104, 101, 108, 108, 111] bytes = [] strio = StringIO.new('тест') # Four 2-byte characters. strio.each_byte {|byte| bytes.push(byte) } bytes # => [209, 130, 208, 181, 209, 129, 209, 130] bytes = [] strio = StringIO.new('こんにちは') # Five 3-byte characters. strio.each_byte {|byte| bytes.push(byte) } bytes # => [227, 129, 147, 227, 130, 147, 227, 129, 171, 227, 129, 161, 227, 129, 175]
The position in the stream matters:
Example
bytes = [] strio = StringIO.new('こんにちは') strio.getc # => "こ" strio.pos # => 3 # 3-byte character was read. strio.each_byte {|byte| bytes.push(byte) } bytes # => [227, 130, 147, 227, 129, 171, 227, 129, 161, 227, 129, 175]
If at end-of-file, does not call the block:
Example
strio.eof? # => true strio.each_byte {|byte| fail 'Boo!' } strio.eof? # => true
With no block given, returns a new Enumerator.
Related: StringIO#each_char, StringIO#each_codepoint, StringIO#each_line.