class method · added in Ruby 3.1
Integer.try_convert
(::int) -> ::Integer
(untyped) -> ::Integer?
Integer.try_convert(object) → object, integer, or nil
numeric.c
View on GitHub ↗
static VALUE
int_s_try_convert(VALUE self, VALUE num)
{
return rb_check_integer_type(num);
}
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
-
3.1
-
Integer.try_convertis added. [Feature #15211]
-