Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

class method · added in Ruby 3.1

Integer.try_convert

(::int) -> ::Integer
(untyped) -> ::Integer?
Integer.try_convert(object) → object, integer, or nil

If object is an Integer object, returns object.

Example
Integer.try_convert(1) # => 1

Otherwise if object responds to :to_int, calls object.to_int and returns the result.

Example
Integer.try_convert(1.25) # => 1

Returns nil if object does not respond to :to_int

Example
Integer.try_convert([]) # => nil

Raises an exception unless object.to_int returns an Integer object.

Ruby version changes

  1. 3.1
See also .sqrt #% #& also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1