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
numeric.rb
View on GitHub ↗
# File tmp/rubies/ruby-3.1.3/numeric.rb, line 247
def Integer.try_convert(num)
=begin
Primitive.attr! 'inline'
Primitive.cexpr! 'rb_check_integer_type(num)'
=end
end
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]
-