split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified.
Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.
ruby
Output:
ruby
Output:
ruby
Output:
Syntax:Example 1:arr = str.split(pattern, limit) publicParameters: arr is the list, str is the string, pattern is the either string or regExp, and limit is the maximum entries into the array. Returns: Array of strings based on the parameters.
# Ruby program to demonstrate split method
# Split without parameters
# Here the pattern is a
# single whitespace
myArray = "Geeks For Geeks".split
puts myArray
Geeks For GeeksExample 2:
# Ruby program to demonstrate split method
# Here pattern is a regular expression
# limit value is 2
# / / is one white space
myArray = "Geeks For Geeks".split(/ /, 2)
puts myArray
Geeks For GeeksExample 3:
# Ruby program to demonstrate split method
# Here the pattern is a regular expression
# limit value is -1
# if the limit is negative there is no
# limit to the number of fields returned,
# and trailing null fields are not
# suppressed.
myArray = "geeks geeks".split('s', -1)
puts myArray
geek geek