Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove email address from string in Ruby

Tags:

string

ruby

I have the following code which is supposed to be removing a particular email address from a string if it exists. The problem is i get the error "invalid range "y-d" in string transliteration (ArgumentError)" which I assume is because it's treating my input as a regex. I will need to do this delete by a variable in the actual code, not a string literal but this is a simplified version of the problem.

So how do I properly perform this operation?

myvar = "[email protected] [email protected]"
myvar = myvar.delete("[email protected]")
like image 913
cjserio Avatar asked Jan 18 '23 04:01

cjserio


2 Answers

Try

myvar = "[email protected] [email protected]"
myvar = myvar.gsub("[email protected]", '').strip
like image 185
Hauleth Avatar answered Jan 27 '23 21:01

Hauleth


String#delete(str) does not delete the literal string str but builds a set out of individual characters of str and deletes all occurrences of these characters. try this:

"sets".delete("test")
=> ""

"sets".delete("est")
=> ""

The hyphen has a special meaning, it defines a range of characters. String#delete("a-d") will delete all occurrences of a,b,c and d characters. Range boundary characters should be given in ascending order: you should write "a-d" but not "d-a".

In your original example, ruby tries to build a character range from y-d substring and fails.

Use String#gsub method instead.

like image 27
Nik O'Lai Avatar answered Jan 27 '23 20:01

Nik O'Lai