I have a string pattern that, as an example, looks like this:
WBA - Skinny Joe vs. Hefty Hal
I want to truncate the pattern "WBA - " from the string and return just "Skinny Joe vs. Hefty Hal".
In Ruby, we can permanently delete characters from a string by using the string. delete method. It returns a new string with the specified characters removed.
Delete - (. Delete is the most familiar Ruby method, and it does exactly what you would think: deletes a sub-string from a string. It will search the whole string and remove all characters that match your substring. The downside of delete is that it can only be used with strings, not RegExs.
If you want to remove only leading and trailing whitespace (like PHP's trim) you can use . strip , but if you want to remove all whitespace, you can use . gsub(/\s+/, "") instead .
Since Ruby 1.9. 2, String#gsub accepts hash as a second parameter for replacement with matched keys. You can use a regular expression to match the substring that needs to be replaced and pass hash for values to be replaced.
Assuming that the "WBA" spot will be a sequence of any letter or number, followed by a space, dash, and space:
str = "WBA - Skinny Joe vs. Hefty Hal" str.sub /^\w+\s-\s/, ''
By the way — RegexPal is a great tool for testing regular expressions like these.
If you need a more complex string replacement, you can look into writing a more sophisticated regular expression. Otherise:
Keep it simple! If you only need to remove "WBA - "
from the beginning of the string, use String#sub
.
s = "WBA - Skinny Joe vs. Hefty Hal" puts s.sub(/^WBA - /, '') # => Skinny Joe vs. Hefty Hal
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With