instance method
StringIO#getc
() -> ::String?
getc → character, byte, or nil
ext/stringio/stringio.c
View on GitHub ↗
static VALUE
strio_getc(VALUE self)
{
struct StringIO *ptr = readable(self);
rb_encoding *enc = get_enc(ptr);
VALUE str = ptr->string;
long pos = ptr->pos;
int len;
char *p;
if (eos_p(ptr)) {
return Qnil;
}
p = RSTRING_PTR(str)+pos;
len = rb_enc_mbclen(p, RSTRING_END(str), enc);
ptr->pos += len;
return enc_subseq(str, pos, len, enc);
}
Reads and returns the next character (or byte; see below) from the stream:
Example
strio = StringIO.new('foo') strio.getc # => "f" strio.getc # => "o" strio.getc # => "o"
Returns nil if at end-of-stream:
Example
strio.eof? # => true strio.getc # => nil
Returns characters, not bytes:
Example
strio = StringIO.new('Привет') strio.getc # => "П" strio.getc # => "р" strio = StringIO.new('こんにちは') strio.getc # => "こ" strio.getc # => "ん"
In each of the examples above, the stream is positioned at the beginning of a character; in other cases that need not be true:
Example
strio = StringIO.new('こんにちは') # Five 3-byte characters. strio.pos = 3 # => 3 # At beginning of second character; returns character. strio.getc # => "ん" strio.pos = 4 # => 4 # At second byte of second character; returns byte. strio.getc # => "\x82" strio.pos = 5 # => 5 # At third byte of second character; returns byte. strio.getc # => "\x93"