Avoid exceptions for typecasting to integer

Posted . Visible to the public.

There's a method Integer() Show archive.org snapshot defined on Kernel, that typecasts everything into an Integer.

Integer("2")  # 2
Integer(nil) # Can't convert nil to Integer (TypeError)
Integer([]) # Can't convert Array into Integer (TypeError)
Integer(Object.new) # Can't convert Object into Integer (TypeError)
Integer(2) # 2
Integer("11", 2) # 3

This is very similar but not identical to to_i:

"2".to_i # 2
nil.to_i # 0
[].to_i # undefined method 'to_i' for an instance of Array (NoMethodError)
Object.new.to_i # undefined method 'to_i' for an instance of Object (NoMethodError)
2.to_i # 2
"11.to_i(2) # 3

Integer() supports a exception: false variant, which is very handy to cast user input without any exception:

Integer("2", exception: false) # 2
Integer(nil, exception: false) # nil
Integer([], exception: false) # nil
Integer(Object.new, exception: false) # nil
Integer(2, exception: false) # 2
Integer("11", 2, exception: false) # 3  

This is typically useful for casting a user defined parameter to an Integer without causing exception notifications:

# can cause exceptions
def show
  # there's no guarantee that params[:page] is something that can be cast to an Integer 
  Record.paginate(page: params[:page]) 
end

# will not raise because of a failed typecast
def show
  Record.paginate(page: Integer(params[:page], exception: false))
end
Niklas Hä.
Last edit
Niklas Hä.
License
Source code in this card is licensed under the MIT License.
Posted by Niklas Hä. to makandra dev (2025-09-17 11:51)