HMLDude
HMLDude

Reputation: 1637

How to remove strings that end with a particular character in Ruby

Based on "How to Delete Strings that Start with Certain Characters in Ruby", I know that the way to remove a string that starts with the character "@" is:

email = email.gsub( /(?:\s|^)@.*/ , "") #removes strings that start with "@"

I want to also remove strings that end in ".". Inspired by "Difference between \A \z and ^ $ in Ruby regular expressions" I came up with:

email = email.gsub( /(?:\s|$).*\./ , "") 

Basically I used gsub to remove the dollar sign for the carrot and reversed the order of the part after the closing parentheses (making sure to escape the period). However, it is not doing the trick.

An example I'd like to match and remove is:

"a8&23q2aas."

Upvotes: 0

Views: 1908

Answers (3)

Ehud
Ehud

Reputation: 105

def replace_suffix(str,suffix)
  str.end_with?(suffix)? str[0, str.length - suffix.length] : str 
end

Upvotes: -2

the Tin Man
the Tin Man

Reputation: 160551

I'd use:

words = %w[@a day in the life.]
# => ["@a", "day", "in", "the", "life."]

words.reject { |w| w.start_with?('@') || w.end_with?('.') }
# => ["day", "in", "the"]

Using a regex is overkill for this if you're only concerned with the starting or ending character, and, in fact, regular expressions will slow your code in comparison with using the built-in methods.

I would really like to stick to using gsub....

gsub is the wrong way to remove an element from an array. It could be used to turn the string into an empty string, but that won't remove that element from the array.

Upvotes: 1

Derrell Durrett
Derrell Durrett

Reputation: 576

You were so close.

email = email.gsub( /.*\.\s*$/ , "")

The difference lies in the fact that you didn't consider the relationship between string of reference and the regex tokens that describe the condition you wish to trigger. Here, you are trying to find a period (\.) which is followed only by whitespace (\s) or the end of the line ($). I would read the regex above as "Any characters of any length followed by a period, followed by any amount of whitespace, followed by the end of the line."

As commenters pointed out, though, there's a simpler way: String#end_with?.

Upvotes: 2

Related Questions