Ruby Convert Types: Arrays and Strings

Cast and converts types: use methods to convert strings, arrays and hashes.

Convert. 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.
Ruby program that converts string to array # Input string has four characters. value = "test" # Split on an empty string delimiter. elements = value.split "" # Display result. puts elements.length puts elements Output 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."
Join: The join method can add separator characters in between the elements of the array.
String Join
Ruby program that converts array to string # The input array has three characters. values = ["a", "b", "c"] # Call join on the array. result = values.join puts result Output abc

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.Hash
Tip: The keys and values methods can be used directly as arrays. They can be looped over or used like any other array.
To_a: 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.
Ruby program that converts hash, array # 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" Output 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.
Ruby program that converts number to string number = 1234 # Convert to String with String method. value = String(number) # Test String value. if value == "1234" puts true end Output true

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.
Ruby program that converts string to Integer value = "1234" # Convert String to Integer. number = Integer(value) # Test Integer for correctness. if number == 1234 puts true end Output true

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.
First: We see a program that tries to convert a non-numeric string ("x") into an Integer. This fails with an ArgumentError.
Second: We wrap those same statements in a begin and rescue block. The program still does not work, but it does not terminate early.
Ruby program that causes ArgumentError # Will not work. value = "x" number = Integer(value) Output file.rb:3:in `Integer': invalid value for Integer(): "x" (ArgumentError) Ruby program that rescues error begin # This is not a valid number string. value = "x" number = Integer(value) rescue # An error is raised. puts "Invalid number" end Output 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.

© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.