Open In App

Ruby - String split() Method with Examples

Last Updated : 03 Jul, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
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.
Syntax:
arr = str.split(pattern, limit) public
Parameters: 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.
Example 1: ruby
# Ruby program to demonstrate split method
 
# Split without parameters
# Here the pattern is a 
# single whitespace
myArray = "Geeks For Geeks".split
puts myArray
Output:
Geeks
For
Geeks
Example 2: ruby
# 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
Output:
Geeks
For Geeks
Example 3: ruby
# 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
Output:
geek
 geek

Next Article
Article Tags :

Similar Reads