In Ruby, we can convert a string to an array by using the split() method.
some_string = "string"
some_string = some_string.split("")
print some_string
#Output:
["s", "t", "r", "i", "n", "g"]
If we want to convert a string with spaces to an array and have each element in the array be separated by spaces, we just have to change the parameter in our split() method to include a space.
Here is the code to do this.
some_string = "this is a string with spaces";
some_string = some_string.split(" ")
print some_string
#Output:
["this", "is", "a", "string", "with", "spaces"]
When working with different objects in Ruby, the ability to be able to convert objects into other objects easily can be useful.
One such case is if you want to convert a string into an array in Ruby.
To convert a string into an array using Ruby, the easiest way is with the split() method.
The split() method creates a new array with elements containing each character of the string.
Below is our simple example again showing you how to convert a string to an array in Ruby.
some_string = "string"
some_string = some_string.split("")
print some_string
#Output:
["s", "t", "r", "i", "n", "g"]
Hopefully this article has been useful for you to learn how to convert a string to array in Ruby.
Leave a Reply