3 ms·
One of my favorite patterns: _, username, domain = */([^@]+)@(.+$)/.match("foo@example.com")
by sofal 17y ago
One of my favorite patterns:
_, username, domain = */([^@]+)@(.+$)/.match("foo@example.com")
- lzell 17y agoNice. I am intrigued by the leading underscore, are you just using that as a throwaway variable? You could get the username and domain on their own with: username, domain = [*/([^@]+)@(.+$)/.match("foo@example.com")][1..-1] And it is super readable.
- twoism 17y agothis works as well... username,domain = */([^@]+)@(.+$)/.match("foo@example.com").captures
- jherdman 17y agoIf you're capturing something you don't want, you can always prefix your match with '?:' to have a non-capturing group. FWIW, I personally prefer the #match method. Some of the examples in this article just make me want to hurt people. Especially usage of $1, $2, etc.
- tierack 17y agoIn that case, /([^@]+)@(.+$)/.match("foo@example.com")[0] returns the whole string matched by the expression, and [1] and [2] return the first and second groups. That's why the throwaway is there. To get rid of the throwaway, this is a possibility: username, domain = */([^@]+)@(.+$)/.match("foo@example.com").captures Of course, your string better match, otherwise you'll get a NoMethodError.
- steveklabnik 17y ago$1 and $2 are probably still there do to Ruby's Perl heritage. I don't particularly mind their use, but that's probably due to my long history with Perl.