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?
Safe navigation operator¶ ↑ &. , called “safe navigation operator”, allows to skip method call when receiver is nil . It returns nil and doesn't evaluate method's arguments if the call is skipped.
In programming languages where the navigation operator (e.g. ".") leads to an error if applied to a null object, the safe navigation operator stops the evaluation of a method/field chain and returns null as the value of the chain expression.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With