What is Ruby string.rpartition()?
Overview
rpartition() searches a string based on a specific match. If a match is found, the function will return a string containing the portion before the given match, the match itself, and the part following the match. This method requires a parameter, which is a string.
Syntax
str.rpartition(match);
Parameters
str: The string that calls the rpartition() method.
match: The match we want to find.
Return value
The return value is a string that contains three strings. These three include the part before the match, the match string, and the part after the match. Two empty strings and str are returned if nothing is found.
Code
# create a stringstr = "Edpresso"# call the `rpartition()` methoda = str.rpartition("p")b = str.rpartition("s")c = str.rpartition("a") # no matchputs "#{a}"puts "#{b}"puts "#{c}"
Explanation
- Line 2: We create a string
str. - Line 5: We use
"p"as a match to partition the string we create. - Line 6: We use
"b"as a match to partition the string we create. - Line 7: We used
"a"to partition the string we create.
"a"is not found in thestrstring.
- Lines 9, 10, and 11: We print the results to the console.
As we can see, all the partitions were returned except for line 11. Here, two empty strings and str were returned.