Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

class method · added in Ruby 3.1

Integer.try_convert

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.4 · 3.3 · 3.2