Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using [] with the Safe Navigation Operator in Ruby

Tags:

ruby

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?

like image 295
Kyle Decot Avatar asked Jan 14 '16 16:01

Kyle Decot


People also ask

What is safe navigation operator Ruby?

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.

What is the purpose of the safe navigation operator?

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.


2 Answers

Just use the ordinary (non-sugar) form.

request.path.match(/\A\/(?<slug>(?!admin|assets)\w+)/)&.[](:slug) 
like image 95
sawa Avatar answered Sep 24 '22 18:09

sawa


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) 
like image 33
Vedant Agarwala Avatar answered Sep 25 '22 18:09

Vedant Agarwala