Support Online
Skip to main content

Guide to Data Type Conversion in Ruby: Switching Between String, Number, Array and Symbol

Ruby offers developers easy manipulation thanks to its flexible data type structure. However, data coming from the API, form or database is usually of string type. In this guide, you will learn how to convert strings to numbers, objects to strings, strings to arrays and symbols in Ruby.

🧠 What Will You Learn in This Guide?

  • string → number conversion with to_i, to_f, Integer()
  • data → string conversion with to_s and interpolation (#{})
  • Convert string to array with the split method
  • String ↔ symbol conversions with to_sym and to_s
  • Detecting incorrect entries and maintaining data integrity

1️⃣ Converting Strings to Numbers

Data received from the user or external source comes as string. Before performing mathematical operations, this data must be converted to numbers.

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

💬 to_i produces integer, to_f produces decimal number.


🧮 Example: Receiving and Adding Numbers from the User

# adder.rb
print "Birinci sayı: "
ilk = gets.chop.to_f
print "İkinci sayı: "
ikinci = gets.chop.to_f

puts "Toplam: #{ilk + ikinci}"

Output:

Birinci sayı: 5
İkinci sayı: 5
Toplam: 10.0

💡 Keyboard inputs are string by default; If it is not converted with to_f, the result will be “5” + “5” = “55”.


⚠️ to_i Method Behavior

to_i stops when it sees a non-numeric character.

"123-abc".to_i # => 123
"abc".to_i # => 0

💬 If the string does not start with a number, the result returns 0. This can lead to errors such as division by zero.


✅ Safer Alternative: Integer() or Float()

Integer("123") # 123
Integer("123abc") # ArgumentError: invalid value

💬 This method maintains data consistency by throwing errors for incorrect input.


2️⃣ Converting Data to String

In program outputs, it is often necessary to convert numerical or object data to string. In Ruby, the to_s method is used for this:

25.to_s # "25"
[1,2,3].to_s # "[1, 2, 3]"
true.to_s # "true"

🎯 Example: Showing User Information

user = "GenixNode"
calories = 100

puts "Tebrikler, #{user}! Bu antrenmanda #{calories} kalori yaktınız."

💬 Interpolation (#{}) automatically calls the to_s method, so no additional conversion is required.

Alternatively:

puts "Tebrikler, " + user + "! " + calories.to_s + " kalori yaktınız."

🧩 Additional Information: inspect Method

inspect can be used to see the value of the variable during the debug phase.

puts [1,2,3].inspect
# Çıktı: [1, 2, 3]

💬 It is preferred in the debugging process, not in the production environment.


3️⃣ Converting Strings to Arrays

You can use the split method to convert a string to an array.

"elma armut muz".split
# => ["elma", "armut", "muz"]

"Kaplan,Büyük Beyaz,Çekiç Kafa".split(",")
# => ["Kaplan", "Büyük Beyaz", "Çekiç Kafa"]

🎯 Example: Parsing and Listing Data

data = "Tiger,Great White,Hammerhead,Whale,Bullhead"
sharks = data.split(",").sort
sharks.each { |shark| puts shark }

Output:

Bullhead
Great White
Hammerhead
Tiger
Whale

💬 split separates the data, sort sorts it, each prints it in a loop.


4️⃣ String ↔ Symbol Conversion

In Ruby, symbols (:symbol) are similar to strings, but are lightweight and immutable structures. It is often used in hash keys.

🔁 Converting Symbol to String

:dil.to_s # "dil"

🔁 Converting String to Symbol

"ilk_isim".to_sym # :ilk_isim

🎯 Example: Converting Form Fields to Symbols

text = "First name"
symbol = text.gsub(" ", "_").downcase.to_sym
# => :first_name

💬 This conversion is ideal for turning form fields into hash keys.


💬 Frequently Asked Questions (FAQ)

1️⃣ What is the difference between to_i and Integer()? to_i returns 0 for incorrect data; Integer() maintains data accuracy by throwing errors.

2️⃣ Why is string interpolation recommended? Provides more readable code, makes to_s conversion automatic.

3️⃣ split by which character does it separate? The default is space; A different separator can be given as a parameter.

4️⃣ Why are symbols effective? Each symbol is loaded into memory only once and can be reused.

5️⃣ Is it possible to convert a string into a letter-by-letter array? Yes, the chars method is used:

"merhaba".chars # => ["m","e","r","h","a","b","a"]

🎯 Result

You are now familiar with basic data type conversions in Ruby:

  • String → Number (to_i, to_f, Integer)
  • Number → String (to_s, interpolation)
  • String → Array (split)
  • String ↔ Symbol (to_s, to_sym)

These techniques reduce the error rate, especially when processing user input or analyzing API data.

💡 Try it: Test these examples in your own Ruby environment by launching a Virtual Server (V-Server) on the GenixNode platform.