-3

I have strings of the following pattern showing up in an array:

"@SomeUselessText"

In this example, I'd like to get rid of all strings in my array that start with the character "@".

This is what I've come up with so far:

def array_purge(array)
  for array.each |item|
    item = item.gsub(/@.*/, "")
  end
end

However, this also gets rid of valid email address of the form:

"info@SomeSite.com"

...which I'd like to keep.

I'm guessing there is an elegant way of handling this. Perhaps using ".reject!"

HMLDude
  • 1,547
  • 7
  • 27
  • 47

4 Answers4

7

The other suggested answers do not in fact purge the targeted items from the array; they merely replace the items with empty strings. More likely you want this:

def array_purge(array)
  array.reject! { |item| item.start_with?('@') }
end

>> array = ['Hello', '123', '@SomeUselessText', 'info@SomeSite.com']
>> array_purge(array)
=> ["Hello", "123", "info@SomeSite.com"]
moveson
  • 5,103
  • 1
  • 15
  • 32
1

You can use Enumerable#grep_v here

array = ['Hello', '123', '@SomeUselessText', 'info@SomeSite.com']
array.grep_v(/\A@/)
 #=> ["Hello", "123", "info@SomeSite.com"]
Sagar Pandya
  • 9,323
  • 2
  • 24
  • 35
0

Check if there's a whitespace (\s) before or if it's the start of the string (^).

(?:\s|^)@.*

Live Demo

If you only want to match word characters, then instead of using . you could use \w. Also note that * would still match just "@", so you might want to use + instead to match at least one character.

(?:\s|^)@\w+

Live Demo

vallentin
  • 23,478
  • 6
  • 59
  • 81
-1

Use the following regular expression [line] instead: a.gsub(/^@.*/, "")

The ^ means "from the start of the line"... so, it only matches if there's the start of the line, then the next character is an @

RyanWilcox
  • 13,890
  • 1
  • 36
  • 60