Convert Types: Arrays and Strings
This page was last reviewed on Jul 12, 2023.
Dot Net Perls
Convert. 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, array. A 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.
Tip By default, the split method separates a string based on a space character. This will not work for a character-level conversion.
String split
# Input string has four characters. value = "test" # Split on an empty string delimiter. elements = value.split "" # Display result. puts elements.length puts elements
4 t e s t
Array, 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.
Here We take an array of three characters, use join, and then have the string "abc."
Tip The join method can add separator characters in between the elements of the array.
# The input array has three characters. values = ["a", "b", "c"] # Call join on the array. result = values.join puts result
Hash. 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.
Tip The keys and values methods can be used directly as arrays. They can be looped over or used like any other array.
Detail The to_a method is also available on a hash. This converts the hash into an array of two-element arrays (pairs).
And This converts a hash to an array (an "a") with no loss of information. All the pairs remain intact.
# 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]]
Number, 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.
Note We show the conversion works by testing against a 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 end
String, integer. Often 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.
Note This receives a 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 end
Invalid 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.
Here We see a program that tries to convert a non-numeric string ("x") into an Integer. This fails with an ArgumentError.
Next We wrap those same statements in a begin and rescue block. The program still does not work, but it does not terminate early.
# 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" end
Invalid number
Converting types is 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jul 12, 2023 (edit).
© 2007-2024 Sam Allen.