Skip to content

Integer(o, exception: false) parses o.to_str leniently: "1---" gives 1 #10107

Open

Description

@taxor03

Integer(o, exception: false) with an object that defines to_str parses the String it returns leniently, so trailing garbage is ignored and an invalid number gives an Integer instead of nil: "1---" gives 1, "12abc" gives 12, and "0x" and "0.0" give 0. The same Strings passed directly give nil, and CRuby gives nil for both. The docs say that with exception: false "an exception of any kind is suppressed and nil is returned" (Kernel#Integer); without exception: false, JRuby already raises ArgumentError for these objects as CRuby does.

def str_like(s) = Object.new.tap { |o| o.define_singleton_method(:to_str) { s } }

["1---", "12abc", "0x", "0.0"].each do |s|
  p [s, Integer(s, exception: false), Integer(str_like(s), exception: false)]
end

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

["1---", nil, nil]
["12abc", nil, nil]
["0x", nil, nil]
["0.0", nil, nil]

JRuby 10.0.8.0 (jruby 10.0.8.0 (3.4.12) 2026-11-05 ef393d4e54 OpenJDK 64-Bit Server VM 21.0.13+9-LTS on 21.0.13+9-LTS +indy +jit [aarch64-linux]):

["1---", nil, 1]
["12abc", nil, 12]
["0x", nil, 0]
["0.0", nil, 0]

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]) and a build of master (54dd973) print the same.

After to_str, TypeConverter.convertToInteger calls ConvertBytes.byteListToInum(context.runtime, bytes, base, exception) (TypeConverter.java#L445; on master TypeConverter.java#L436). The last parameter of that 4-argument overload is badcheck, not exception (ConvertBytes.java#L365; on master ConvertBytes.java#L359), so exception: false turns off the check for trailing characters. CRuby's rb_convert_to_integer calls rb_str_convert_to_inum(tmp, base, TRUE, raise_exception) there (object.c#L3456); the 5-argument byteListToInum(runtime, bytes, base, true, exception) would match it.

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