Search code examples
ruby

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?


Solution

  • Just use the ordinary (non-sugar) form.

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