split a string into an array of substrings in ruby

To split a string into an array of substrings in Ruby, you can use the .split method. This method returns an array of substrings, split by a specified delimiter.

For example, let's say you have the following string:

main.rb
my_string = "Hello, how are you today?"
40 chars
2 lines

You can split this string into an array of substrings based on the delimiter , (comma and space) by calling the .split method like this:

main.rb
my_array = my_string.split(", ")
33 chars
2 lines

This will split the string at each occurrence of a comma followed by a space, resulting in the following array:

main.rb
["Hello", "how are you today?"]
32 chars
2 lines

You can also split a string by other delimiters, such as whitespace or a hyphen, by passing the delimiter as an argument to the .split method:

main.rb
my_string = "this-is-a-string"
my_array = my_string.split("-")
63 chars
3 lines

This will split the string at each occurrence of a hyphen, resulting in the following array:

main.rb
["this", "is", "a", "string"]
30 chars
2 lines

gistlibby LogSnag