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 "user@example.com" 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 ??
You can split on "@" and just use the first part.
email.split("@")[0]
That will give you the first part before the "@".
To catch anything before the @ sign:
my_string = "user@example.com"
substring = my_string[/[^@]+/]
# => "user"
Just split at the @ symbol and grab what went before it.
string.split('@')[0]
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 = test@testing.com
e.split("@")
#=> ["test", "testing.com"]
Thus you would take e.split("@")[0]
for the first part of the address.
use gsub and a regular expression
first_name = email.gsub(/@[^\s]+/,"")
irb(main):011:0> Benchmark.bmbm do |x|
irb(main):012:1* email = "user@domain.type"
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>]
精彩评论