Ruby Casting

christian.dinh's avatar
Published Jul 30, 2021Updated May 15, 2024

In Ruby, the language comes with a variety of building typecasting methods for converting values from one data type to another.

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn to program in Ruby, a flexible and beginner-friendly language used to create sites like Codecademy.
    • Beginner Friendly.
      9 hours

Syntax

For the most part methods usually begin with to_[data-type].

To Integer

To convert from String to Integer, use to_i:

meaning_of_life = "42"
puts meaning_of_life.class # Output: String
meaning_of_life = meaning_of_life.to_i
puts meaning_of_life.class # Output: Integer

To Float

To convert from String to Float-type, use to_f:

meaning_of_life = "42.0"
puts meaning_of_life.class # Output: String
meaning_of_life = meaning_of_life.to_f
puts meaning_of_life.class # Output: Float

To Array

To convert an Object to an Array, use to_a:

myObj = {
name: "Denise",
occupation: "Software Engineer"
}
puts myObj.to_a

The output would be:

name
Denise
occupation
Software Engineer

All contributors

Learn Ruby on Codecademy

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn to program in Ruby, a flexible and beginner-friendly language used to create sites like Codecademy.
    • Beginner Friendly.
      9 hours