Forum: Ruby Extracting information from "john-2222-8888@domain.com"

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
2c2f3ce7125411ff78a1d3e902aa2a4d?d=identicon&s=25 Bob Sanders (adistarmid)
on 2008-10-25 23:44
Hello,

I'm wondering how you'd extract information from an email address like
"john-2222-8888@domain.com" to get these results from that email:

@player_id = 2222
@game_id = 8888

I'm thinking it's something along the lines of:

email = john-2222-8888@domain.com
@player_id = email.gsub(...)
@game_id = email.gsub(...)

Any ideas what belongs in the gsubs?
A61ecce13ed142622f24a5ca3a123922?d=identicon&s=25 Matthew Moss (Guest)
on 2008-10-25 23:52
(Received via mailing list)
> @game_id = email.gsub(...)
>
> Any ideas what belongs in the gsubs?

Sounds more like a job for regexp pattern matching:

    @player_id, @game_id = email.match(/.+-(\d+)-(\d
+)@domain.com/).captures
    => ["2222", "8888"]

    @player_id
    => "2222"

    @game_id
    => "8888"

You can get more specific with the regexp pattern; the one above I
just threw together quickly.
2c2f3ce7125411ff78a1d3e902aa2a4d?d=identicon&s=25 Bob Sanders (adistarmid)
on 2008-10-26 00:10
That works perfectly. Thank you, Matthew!!
2ee1a7960cc761a6e92efb5000c0f2c9?d=identicon&s=25 William James (Guest)
on 2008-10-26 01:20
(Received via mailing list)
Bob Sanders wrote:

> "john-2222-8888@domain.com"

C:\>irb --prompt xmp
player,game = "john-2222-8888@domain.com".split(/[-@]/)[1,2]
    ==>["2222", "8888"]
player
    ==>"2222"
game
    ==>"8888"
This topic is locked and can not be replied to.