Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 31 / 68

Type Conversion (Casting) Basics

In this lesson you will learn the basics of type conversion in Ruby so you can move correctly between strings and numbers. This is for anyone searching for "Ruby type conversion to_i to_s".

Type conversion (casting) - string to number, number to string - is a fundamental programming operation. You use .to_i, .to_s, and .to_f. Input from a user always arrives as text, so it must be converted before you can calculate with it.

The sample code turns the string "123" into a number with .to_i and uses it in arithmetic, then turns the number 45 into a string with .to_s and joins it to the word "dollars". Chaining a method onto a value with a dot is consistent, idiomatic Ruby.

A common stumbling block for beginners is what happens when the conversion fails. A string that cannot be converted to a number becomes 0, so instead of an error you quietly get the wrong value. Check first where it matters.

In real-world development, values coming from a form are always strings, so you must convert before doing monetary or date arithmetic. Type-aware code is the foundation of a stable application with fewer bugs.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)