String.to_i / to_f / to_sym / inspect
Methods that convert a string to another type, such as an integer, a floating-point number, or a symbol.
Syntax
# Converts a string to an integer. string.to_i string.to_i(base) # Interprets the string as a number in the given base (2–36). # Converts a string to a floating-point number. string.to_f # Converts a string to a symbol. string.to_sym # Returns a debug representation of the string (includes quotes and escaped characters). string.inspect
Method list
| Method | Description |
|---|---|
| to_i | Converts a string to a base-10 integer. Reads as many leading characters as possible; returns 0 if no conversion is possible. |
| to_i(base) | Interprets the string in the specified base (e.g., binary or hexadecimal) and converts it to an integer. |
| to_f | Converts a string to a floating-point number. Returns 0.0 if no conversion is possible. |
| to_sym | Converts a string to a symbol. Symbols are commonly used as hash keys and identifiers. |
| inspect | Returns a debug-friendly representation of the string, including surrounding quotes and escaped special characters. |
Sample code
# Converting strings to integers. puts "42".to_i # 42 puts "3.14".to_i # 3 (decimal part is truncated) puts "123abc".to_i # 123 (stops at the first non-numeric character) puts "abc".to_i # 0 (returns 0 when no conversion is possible) # Converting with a specified base. puts "ff".to_i(16) # 255 (interpreted as hexadecimal) puts "1010".to_i(2) # 10 (interpreted as binary) # Converting strings to floating-point numbers. puts "3.14".to_f # 3.14 puts "1.5e2".to_f # 150.0 (scientific notation is supported) puts "abc".to_f # 0.0 # Converting to a symbol. key = "name" sym = key.to_sym puts sym # name puts sym.class # Symbol # Using inspect to see the internal representation of a string. text = "Hello\nWorld" puts text # Hello (newline) World puts text.inspect # "Hello\nWorld" (escaped output)
Notes
Ruby's type conversion methods are lenient by design — they do not raise an exception when the string cannot be converted, and instead return 0 or 0.0. If you need strict conversion (i.e., you want an error when the string is invalid), use the Kernel methods 『Integer()』 or 『Float()』. These raise an 『ArgumentError』 when the conversion fails.
Symbols are similar to strings, but any two symbols with the same content share a single object in memory, making them efficient to use as hash keys and identifiers. To convert a symbol back to a string, use 『Symbol#to_s』.
For string formatting, see 『sprintf() / % operator』. For encoding conversion, see 『encoding / encode』.
If you find any errors or copyright issues, please contact us.