Project

General

Profile

Actions

Bug #22080

open

`Integer(obj, exception: false)` raises when `to_str` doesn't return String

Bug #22080: `Integer(obj, exception: false)` raises when `to_str` doesn't return String

Added by Earlopain (Earlopain _) about 2 hours ago.

Status:
Open
Assignee:
-
Target version:
-
ruby -v:
ruby 4.1.0dev (2026-05-23T13:04:55Z master 6c6df00bbc) +PRISM [x86_64-linux]
[ruby-core:125572]

Description

obj = Object.new
def obj.to_str = 1

Integer(obj, exception: false) # can't convert Object to String (Object#to_str gives Integer) (TypeError)

But returning the wrong type from to_int is fine:

obj = Object.new
def obj.to_int = "1"

Integer(obj, exception: false) # nil

Doc says this (https://docs.ruby-lang.org/en/master/Kernel.html#method-i-Integer):

With exception given as false, an exception of any kind is suppressed and nil is returned.

So it looks like it should not raise in both cases. Or more specifically, try to_i next, since that is what happens when to_int returns the wrong type.


Related issues 1 (0 open1 closed)

Related to Ruby - Bug #18998: Kernel#Integer does not convert SimpleDelegator object expectlyClosedActions

Updated by Earlopain (Earlopain _) about 2 hours ago Actions #1

  • Related to Bug #18998: Kernel#Integer does not convert SimpleDelegator object expectly added
Actions

Also available in: PDF Atom