Ruby: Avoiding errors when casting user input to Integers

Updated . 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("foo")  # Invalid value for Integer() (ArgumentError)
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
"foo".to_i # 0
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("foo", exception: false) # nil
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

Alternative: Cast with ActiveModel

If you have ActiveModel you can also use the same casting rules of your ActiveRecord attributes:

ActiveModel::Type::Integer.new.cast("2")  # 2
ActiveModel::Type::Integer.new.cast(nil) # nil
ActiveModel::Type::Integer.new.cast([]) # nil
ActiveModel::Type::Integer.new.cast(Object.new) # nil
ActiveModel::Type::Integer.new.cast(2) # 2

Similiar casting rules are available for other types, like ActiveModel::Type::Boolean or ActiveModel::Type::Date.

Profile picture of Niklas Hä.
Niklas Hä.
Last edit
Henning Koch
Keywords
cast, casting, exception
License
Source code in this card is licensed under the MIT License.
Posted by Niklas Hä. to makandra dev (2025-09-17 11:51)