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 string
str = "Edpresso"
# call the `rpartition()` method
a = str.rpartition("p")
b = str.rpartition("s")
c = str.rpartition("a") # no match
puts "#{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 the str string.

  • 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.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources