Skip to the workspace
Pebellslearn by building
Data Types  ›  Capstone Project

Type Casting

Type Casting 15 minExplicit conversion methods such as to_i, to_f and to_s produce another representation. Integer and Float provide stricter numeric conversion; other operations may apply their own coercion rules.

ruby / Type Casting

Explore each scene at your own pace.

01 · The rule

The rule

Type Casting

Explicit conversion methods such as to_i, to_f and to_s produce another representation. Integer and Float provide stricter numeric conversion; other operations may apply their own coercion rules.

Compare permissive conversion helpers with stricter parsing at an input boundary.

A customer types "3" into Bean Cart's order form. The form hands your code the string "3", not the number 3, and 4.50 * "3" is an error. Converting between types, often called type casting, is a daily job. Ruby gives you two styles: a forgiving one and a strict one.

The rule

to_ methods forgive; capitalised Integer() and Float() complain.

Ruby rarely converts types behind your back. Mixing a number and a string raises a TypeError:

1 + "2"    # TypeError: String can't be coerced into Integer
"2" + 1    # TypeError: no implicit conversion of Integer into String

So you convert explicitly. The forgiving methods start with to_. They always return something, even if the input is nonsense:

"3".to_i        # => 3
"4.50".to_f     # => 4.5
"3 lattes".to_i # => 3   (reads leading digits, ignores the rest)
"latte".to_i    # => 0   (no digits at all)
12.to_s         # => "12"
3.to_f          # => 3.0
3.99.to_i       # => 3   (cuts off the decimals, no rounding)
:tea.to_s       # => "tea"
"tea".to_sym    # => :tea

The strict conversions are methods named like classes. They raise an error if the whole input is not a valid number:

Integer("3")        # => 3
Integer("3 lattes") # ArgumentError: invalid value for Integer()
Float("4.50")       # => 4.5
Float("")           # ArgumentError
Integer("3 lattes", exception: false)  # => nil

The last form returns nil instead of raising, which is handy for checking input.

When building text, you rarely need to_s at all: interpolation calls it for you, so "Cups: #{12}" works.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.