C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: By default, the split method separates a string based on a space character. This will not work for a character-level conversion.
SplitRuby 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
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 JoinRuby 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
Tip: The keys and values methods can be used directly as arrays. They can be looped over or used like any other array.
ArrayTo_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]]
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
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
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