Skip to content

ARGF.getc and ARGF.readchar return byte Integers instead of one-character Strings #10032

Open

Description

@taxor03

When ARGF reads from files named on the command line, ARGF.getc and ARGF.readchar return the next byte as an Integer (104), not the next character as a String ("h"). A multibyte character comes back as several Integers, one per byte. The docs say both "Reads the next character from ARGF and returns it as a String" and show ARGF.getc #=> "f" (ARGF#getc, ARGF#readchar). A loop that builds a String with s << c still works for ASCII, because String#<< accepts an Integer codepoint, but it silently turns é into é. c == "h" is never true, and String methods on c raise NoMethodError.

# repro.rb, run as: ruby repro.rb input.txt
# input.txt contains "hé\nhé\n" (UTF-8)
p ARGF.getc
p ARGF.readchar
p ARGF.getc

s = +""
while (c = ARGF.getc)
  s << c
end
p s

CRuby 4.0.9 (ruby 4.0.9 (2026-10-23 revision 3e93b23afc) +PRISM [aarch64-linux]), and 3.4.12 prints the same:

"h"
"é"
"\n"
"hé\n"

JRuby 10.1.3.0 (jruby 10.1.3.0 (4.0.9) 2026-11-05 3db52d02f9 OpenJDK 64-Bit Server VM 21.0.13+9-LTS on 21.0.13+9-LTS +indy +jit [aarch64-linux]):

104
195
169
"\nhé\n"

JRuby 10.1.2.0 and the nightly 10.1.4.0-SNAPSHOT (5daf993, 2026-11-07) print the same. With input from stdin (ruby repro.rb < input.txt) JRuby prints the same as CRuby, and File#getc on the same file returns "h".

When the current file is a RubyFile, RubyArgsFile#getc calls getbyte on it; only other kinds of input (stdin, for example) go through getc (RubyArgsFile.java#L891-L895). readchar is built on that getc (#L793-L800). This looks like Ruby 1.8 behavior that was kept: up to 9.2 the call was RubyIO#getc(), a deprecated method that returned getbyte, and c10d686 replaced it with getbyte(context) directly. CRuby's argf_getc and argf_readchar call rb_io_getc on a file (io.c#L14121-L14140). Calling RubyIO#getc(context) there should match it. each_byte and each_char in the same file call this getc too, so they would need to switch to getbyte if getc changes.

ruby/spec's core/argf/shared/getc.rb builds the result with chars << @argf.send(@method) from ASCII fixtures and compares it with the file contents, and an Integer passes that (getc.rb#L10-L16). CRuby's test_getc and test_readchar in test/ruby/test_argf.rb do the same with s << c, so neither catches this.

Found while comparing JRuby with CRuby on ruby/spec-based checks.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions