Using [] with Safe Navigation Operator in Ruby

I currently have a piece of code that looks like this:

if match = request.path.match(/\A\/(?<slug>(?!admin|assets)\w+)/) match[:slug] end 

Is there a way to use the safe navigation operator (introduced in 2.3.0) to avoid this if conditional?

+6
source share
3 answers

Just use the regular (non-sugar) form.

 request.path.match(/\A\/(?<slug>(?!admin|assets)\w+)/)&.[](:slug) 
+10
source

You can use send any method, so with a secure browser it will be:

 request.path.match(/\A\/(?<slug>(?!admin|assets)\w+)/)&.send(:[], :slug) 
+2
source

For better readability, I chose #dig instead of #[] .

how

 request.path.match(/\A\/(?<slug>(?!admin|assets)\w+)/)&.dig(:slug) 

instead

 request.path.match(/\A\/(?<slug>(?!admin|assets)\w+)/)&.[](:slug) 
+1
source