Smoke
Smoke

Reputation: 1062

Remove "@" sign and everything after it in Ruby

I am working on an application where I need to pass on the anything before "@" sign from the user's email address as his/her first name and last name. For example if the user has an email address "[email protected]" than when the user submits the form I remove "@example.com" from the email and assign "user" as the first and last name.

I have done research but was not able to find a way of doing this in Ruby. Any suggestions ??

Upvotes: 28

Views: 22933

Answers (5)

Tim Hoolihan
Tim Hoolihan

Reputation: 12396

use gsub and a regular expression

first_name = email.gsub(/@[^\s]+/,"")



irb(main):011:0> Benchmark.bmbm do |x|
irb(main):012:1* email = "[email protected]"
irb(main):013:1> x.report("split"){100.times{|n| first_name = email.split("@")[0]}}
irb(main):014:1> x.report("regex"){100.times{|n| first_name = email.gsub(/@[a-z.]+/,"")}}
irb(main):015:1> end
Rehearsal -----------------------------------------
split   0.000000   0.000000   0.000000 (  0.000000)
regex   0.000000   0.000000   0.000000 (  0.001000)
-------------------------------- total: 0.000000sec

            user     system      total        real
split   0.000000   0.000000   0.000000 (  0.001000)
regex   0.000000   0.000000   0.000000 (  0.000000)
=> [#<Benchmark::Tms:0x490b810 @label="", @stime=0.0, @real=0.00100016593933105, @utime=0.0, @cstime=0.0, @total=0.0, @cutime=0.0>, #<Benchmark::Tms:0x4910bb0 @
label="", @stime=0.0, @real=0.0, @utime=0.0, @cstime=0.0, @total=0.0, @cutime=0.0>]

Upvotes: 1

Pygmalion
Pygmalion

Reputation: 692

The String#split will be useful. Given a string and an argument, it returns an array splitting the string up into separate elements on that String. So if you had:

e = [email protected]
e.split("@")
 #=> ["test", "testing.com"]

Thus you would take e.split("@")[0] for the first part of the address.

Upvotes: 8

Dylan Markow
Dylan Markow

Reputation: 124419

To catch anything before the @ sign:

my_string = "[email protected]"
substring = my_string[/[^@]+/]
# => "user"

Upvotes: 48

J Lundberg
J Lundberg

Reputation: 2363

You can split on "@" and just use the first part.

email.split("@")[0]

That will give you the first part before the "@".

Upvotes: 52

Chuck
Chuck

Reputation: 237060

Just split at the @ symbol and grab what went before it.

string.split('@')[0]

Upvotes: 13

Related Questions