In Ruby a custom method can convert types—but this is rarely needed. We instead use built-in methods to convert common types like strings, arrays and hashes.
When possible, built-in methods are a good choice. They cover many edge cases, so you may need to make fewer changes. And they are fast to test and deploy.
String
, arrayA string
can be converted to an array of characters with the split method. Here, we use a string
that has 4 characters. After splitting, we have an array of 4 values.
string
based on a space character. This will not work for a character-level conversion.# Input string has four characters. value = "test" # Split on an empty string delimiter. elements = value.split "" # Display result. puts elements.length puts elements4 t e s t
string
The join method combines elements of an array together into a new string
. This is an ideal way to convert an array into a string
.
string
"abc."# The input array has three characters. values = ["a", "b", "c"] # Call join on the array. result = values.join puts resultabc
This example is somewhat more complex. It introduces a hash, and then converts the keys and values into arrays and strings. So we get a string
of all the keys, and one of the values.
# An example hash. hash = {"a" => 1, "b" => 2, "c" => 3} # Convert keys into a string. result = hash.keys.join print "KEYS: ", result, "\n" # Convert values into a string. result = hash.values.join print "VALUES: ", result, "\n" # Convert entire hash into an array. elements = hash.to_a print "ARRAY LENGTH: ", elements.length, "\n" print "ARRAY : ", elements, "\n"KEYS: abc VALUES: 123 ARRAY LENGTH: 3 ARRAY : [["a", 1], ["b", 2], ["c", 3]]
string
Numbers can be converted into Strings with the String
method. This receives a numeric variable and returns a String
. It works on integers and floating-point values.
string
"1234." This is a string
-based comparison.number = 1234 # Convert to String with String method. value = String(number) # Test String value. if value == "1234" puts true endtrue
String
, integerOften a program reads in a file that contains numbers, or a use renters a number stored as a string
. We convert these strings with the Integer built-in method.
String
, and if valid, returns an Integer. Please check the next examples to deal with invalid Strings.value = "1234" # Convert String to Integer. number = Integer(value) # Test Integer for correctness. if number == 1234 puts true endtrue
string
We encounter an ArgumentError
if we try to convert a non-numeric String
to an Integer. We can work around this problem with a begin and raise block.
string
("x") into an Integer. This fails with an ArgumentError
.# Will not work. value = "x" number = Integer(value)file.rb:3:in `Integer': invalid value for Integer(): "x" (ArgumentError)begin # This is not a valid number string. value = "x" number = Integer(value) rescue # An error is raised. puts "Invalid number" endInvalid number
Converting types is an uninteresting task, but it is necessary. With this knowledge, we can focus more on core program design. And this focus leads to better, higher-quality programs.