Skip to content
instance method

StringIO#each_char

() { (::String arg0) -> untyped } -> self
() -> ::Enumerator[::String, self]
each_char {|char| ... } → self

With a block given, calls the block with each remaining character in the stream; positions the stream at end-of-file; returns self:

Example
chars = []
strio = StringIO.new('hello')
strio.each_char {|char| chars.push(char) }
strio.eof? # => true
chars      # => ["h", "e", "l", "l", "o"]
chars = []
strio = StringIO.new('тест')
strio.each_char {|char| chars.push(char) }
chars      # => ["т", "е", "с", "т"]
chars = []
strio = StringIO.new('こんにちは')
strio.each_char {|char| chars.push(char) }
chars      # => ["こ", "ん", "に", "ち", "は"]

Stream position matters:

Example
chars = []
strio = StringIO.new('こんにちは')
strio.getc # => "こ"
strio.pos  # => 3  # 3-byte character was read.
strio.each_char {|char| chars.push(char) }
chars      # => ["ん", "に", "ち", "は"]

When at end-of-stream does not call the block:

Example
strio.eof? # => true
strio.each_char {|char| fail 'Boo!' }
strio.eof? # => true

With no block given, returns a new Enumerator.

Related: StringIO#each_byte, StringIO#each_codepoint, StringIO#each_line.

See also #each_byte #each_codepoint #each #each_line also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0