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) 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.
Example 1:
# 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 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 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
Recommended Posts:
- Ruby | BigDecimal split() function
- Ruby | String inspect Method
- Ruby | String hex Method
- Ruby | String include? Method
- Ruby | String delete_suffix! Method
- Ruby | String dump Method
- Ruby | String each_byte Method
- Ruby | String * Method
- Ruby | String + Method
- Ruby | String << Method
- Ruby | String insert Method
- Ruby | String chomp! Method
- Ruby | String chop! Method
- Ruby | String chop Method
- Ruby | String capitalize() Method
- Ruby | String capitalize! Method
- Ruby | String casecmp Method
- Ruby | String casecmp? Method
- Ruby | String length Method
- Ruby | String reverse Method
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.

