Skip to content
instance method

String#to_i

(?::int radix) -> ::Integer
to_i(base = 10) → integer

Returns the result of interpreting leading characters in self as an integer in the given base; base must be either 0 or in range (2..36):

Example
'123456'.to_i     # => 123456
'123def'.to_i(16) # => 1195503

With base zero given, string object may contain leading characters to specify the actual base:

Example
'123def'.to_i(0)   # => 123
'0123def'.to_i(0)  # => 83
'0b123def'.to_i(0) # => 1
'0o123def'.to_i(0) # => 83
'0d123def'.to_i(0) # => 123
'0x123def'.to_i(0) # => 1195503

Characters past a leading valid number (in the given base) are ignored:

Example
'12.345'.to_i   # => 12
'12345'.to_i(2) # => 1

Returns zero if there is no leading valid number:

Example
'abcdef'.to_i # => 0
'2'.to_i(2)   # => 0

Related: see Converting to Non-String.

See also #to_f #to_json_raw #to_c #to_json_raw_object also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0