I currently have a piece of code that looks like:
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?
I currently have a piece of code that looks like:
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?
Just use the ordinary (non-sugar) form.
request.path.match(/\A\/(?<slug>(?!admin|assets)\w+)/)&.[](:slug)
For better readability I would pick #dig
instead of the #[]
.
Like,
request.path.match(/\A\/(?<slug>(?!admin|assets)\w+)/)&.dig(:slug)
instead of
request.path.match(/\A\/(?<slug>(?!admin|assets)\w+)/)&.[](:slug)
For readability, I prefer using the match's named_captures method which is available from ruby 1.9.1, with the safe operator which is available from ruby 2.3.0.
request.path.match(/\A\/(?<slug>(?!admin|assets)\w+)/)&.named_captures&.dig('slug')
You can send
any method, so using safe-browsing operator this will be:
request.path.match(/\A\/(?<slug>(?!admin|assets)\w+)/)&.send(:[], :slug)