Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to extract groups from a regex match in Ruby without globals or temporary variables. Code snippets supporting http://blog.samstokes.co.uk/post/251167556/regex-style-in-ruby
if "foo@example.com" =~ /@(.*)/
$1
else
raise "bad email"
end
# => "example.com"
match = /@(.*)/.match("foo@example.com")
if match
match[1]
else
raise "bad email"
end
# => "example.com"
$1 if "foo@example.com" =~ /@(.*)/ or raise "bad email" # => "example.com"
require 'andand'
/@(.*)/.match("foo@example.com").andand[1] # => "example.com"
"foo@example.com"[/@(.*)/, 1] or raise "bad email"
# => "example.com"
@joshuapinter

This comment has been minimized.

Copy link

joshuapinter commented Dec 8, 2018

I found that match = /@(.*)/.match("foo@example.com") gave different results than "foo@example.com" =~ /@(.*)/.

Same Regex and same body but result was different so ended up using =~.

I take it back. I might not have been using .captures after using .match(). It works great, actually.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.