String match first capture shorthand without raising an error

13
July, 2021

💣 When dealing with empty match:

"1. Price 3EUR".match(/(\d+)EUR/)[1]
# => 3

"1. Price EUR".match(/(\d+)EUR/)
# => This will throw an error


😎 Use:

"1. Price EUR"[/(\d+)EUR/, 1]
# => nil


👎 To avoid following situations:

# Possible solutions

# Rescue
"1. Price EUR".match(/(\d+)EUR/)[1] rescue nil
# => nil

# Global match
"1. Price EUR".match(/(\d+)EUR/) && $1
# => nil

# Variable
result = "1. Price EUR".match(/(\d+)EUR/)
result && result[1]