split a string into two strings in ruby

You can split a string into two strings using the split method or regex. Here's an example of each:

  1. split method:
main.rb
string = "hello world"
first_half, second_half = string.split(' ', 2)
puts first_half # "hello"
puts second_half # "world"
123 chars
5 lines

In this example, we used the split method to split the string "hello world" into two strings based on the space character. The second argument provided to split is the maximum number of splits to perform. Since we only want to split the string into two parts, we pass in 2.

  1. Regex:
main.rb
string = "hello world"
first_half, second_half = string.match(/(.+)\s+(.+)/)[1,2]
puts first_half # "hello"
puts second_half # "world"
135 chars
5 lines

In this example, we use Ruby's regex capabilities to split the string into two parts using a capturing group (.+). The \s+ matches one or more whitespace characters. We then access the captured groups using the [1, 2] array slice.

gistlibby LogSnag