Kyle Decot
Kyle Decot

Reputation: 20815

Using [] with the Safe Navigation Operator in 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?

Upvotes: 52

Views: 22687

Answers (5)

lunarfyre
lunarfyre

Reputation: 1736

A more slightly more readable way to do this instead of safe navigation is with the built in String#[] operator like so:

a = "apple"
b = "bat"

a[/a(p)/, 1] #=> 'p'
b[/a(p)/, 1] #=> nil

Upvotes: 1

Mike State
Mike State

Reputation: 539

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')

Upvotes: 8

Vedant Agarwala
Vedant Agarwala

Reputation: 18819

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)

Upvotes: 27

sawa
sawa

Reputation: 168179

Just use the ordinary (non-sugar) form.

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

Upvotes: 77

Vasfed
Vasfed

Reputation: 18474

You can send any method, so using safe-browsing operator this will be:

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

Upvotes: 4

Related Questions