Ruby – String split() Method with Examples

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program to demonstrate split method
   
# Split without parameters
# Here the pattern is a 
# single whitespace
myArray = "Geeks For Geeks".split
puts myArray

chevron_right


Output:

Geeks
For
Geeks

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


Output:

Geeks
For Geeks

Example 3:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


Output:

geek
 geek



My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.