Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
typecast
data type

How type casting (or type conversion) is done in Ruby

Sheza Munir

When writing code, different data types are often used for different purposes. Ruby allows the user to explicitly or implicitly typecast datatypes. Here, we will go over the following conversions:

  • strings to numbers
  • any other types to strings
  • strings to arrays
  • strings to symbols
  • symbols to strings
  • Strings to numbers:
    The user can convert strings to ints or floats by using the methods to_i and to_f, respectively.

  • Other types to string:
    The user can convert other datatypes to string by using the to_s method.

  • Strings to arrays:
    The split method converts any string to an array.

  • Strings to symbols:
    Strings can be converted to symbols by using the to_sym method.

  • Symbols to strings:
    Symbols can be converted to strings by using the to_s method.

Code

The following code walks through the explanations provided above.

# converting from string to int 

num1 = "5"
num2 = "4"

sum = num1 + num2

print "Without conversion only concatenation of strings is done.\nSum = "
print sum

int_sum = num1.to_i + num2.to_i

print "\nWith conversion to integer arithmetic operations can be done.\nSum = "
print int_sum, "\n"

# converting from any datatype to strings

myarray = ["This", "is", "a", "shot."]
myarray_string = myarray.to_s
print "Array to string: ", myarray_string, "\n"

#converting from strings to arrays

sentence = "This is a shot."
arr = sentence.split
print "String to array: ", arr, "\n"

# converting from string to symbol

string = "smiley_face"
symbol = string.to_sym
print "String to symbol: ", symbol

RELATED TAGS

ruby
typecast
data type

CONTRIBUTOR

Sheza Munir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring