Tutorials  /  Linux Basics

How To Convert Data Types in Ruby

Ccentron Redaktion · January 2025 ·4 min read ·Linux Basics, Tutorial

Introduction to Convert Data Types

While each program you create will contain multiple data types, it is important to keep in mind that you will generally be performing operations within the same data type. That is, you’ll be performing mathematics on numbers, or joining strings together.

Sometimes data comes from external sources, such as the keyboard, an API response, or a database, and you’ll need to convert it in order to work with it. Ruby provides several methods for converting values from one data type to another. In this tutorial, you’ll convert strings to numbers, objects to strings, strings to arrays, and convert between strings and symbols.

VM

Matching infrastructure at centron

No hardware needed to follow along: ccloud³ VMs with full root access start at €3.12 per month, billed by the hour and ready in seconds. Rent a cloud server →

Converting Strings to Numbers

Ruby provides the to_i and to_f methods to Convert Data Types, for example strings to numbers. to_i converts a string to an integer, and to_f converts a string to a float.

Code
"5".to_i       # 5
"55.5".to_i    # 55
"55.5".to_f    # 55.5

To demonstrate this, create a small program that prompts for two numbers and displays the sum. Create a new Ruby program called adder.rb with the following code:

Code
adder.rb
print "What is the first number? "
first_number = gets.chop

print "What is the second number? "
second_number = gets.chop

sum = first_number + second_number

print sum

When you run the program, you’ll get what may feel like an unexpected answer:

Code
ruby adder.rb
Output
What is the first number? 5
What is the second number? 5
55

This program says that the sum of 5 and 5 is 55. You know that’s not right, but the computer isn’t technically wrong. The program prompted for two numbers, but you typed them in on the keyboard. You didn’t send the number 5; you sent the character "5". In other words, your program saw both of your inputs as strings, and when you add the strings "5" and "5" together, you get a new string, "55".

To avoid this, convert both strings to numbers. Modify your program so that it converts both numbers to floats by using the to_f method:

Code
adder.rb
print "What is the first number? "
first_number = gets.chop

print "What is the second number? "
second_number = gets.chop

# convert strings to numbers
first_number = first_number.to_f
second_number = second_number.to_f

sum = first_number + second_number

print sum

Run the program again:

Code
ruby adder.rb
Output
What is the first number? 5
What is the second number? 5
10.0

When you enter 5 and 5 again, you’ll get 10.0.

Special Behavior of to_i and to_f

The to_i and to_f methods have some interesting behaviors when the strings aren’t numeric. For example:

Code
"123-abc".to_i
Output
123

In this example, converting the string "123-abc" to an integer results in the integer 123. The to_i method stops once it reaches the first non-numeric character.

Convert Data Types to Strings

Ruby provides the to_s method to convert any other type to a string:

Code
25.to_s                    # "25"
(25.5).to_s                # "25.5"
["Sammy", "Shark"].to_s    # "[\"Sammy\", \"Shark\"]"

You’ll often convert data to strings when creating program output.

Convert Data Types to Arrays

If you have a string, you can convert it to an array using the split method:

Code
"one two three".split
Output
["one", "two", "three"]

Converting Between Strings and Symbols

To Convert Data Types for example a symbol to a string, use the to_s method:

Code
:language.to_s
Output
"language"

To convert a string to a symbol, use the to_sym method:

Code
"first_name".to_sym
Output
:first_name

Conclusion for Convert Data Types

This tutorial demonstrated how to convert several of the important native data types to other data types using built-in methods. You can now convert numbers to strings, strings to arrays, and convert between symbols and strings.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Linux Basics
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren