在Ruby中使用带有安全导航操作符的[]

时间:2022-08-30 11:50:15

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?

有没有办法使用安全导航操作符(在2.3.0中引入),以避免这种情况有条件?

4 个解决方案

#1


16  

Just use the ordinary (non-sugar) form.

只需使用普通(非糖)形式。

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

#2


2  

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

您可以发送任何方法,因此使用安全浏览操作符将是:

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

#3


2  

For better readability I would pick #dig instead of the #[].

为了更好的可读性,我会选择#dig而不是#[]。

Like,

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

instead of

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

#4


1  

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.

为了便于阅读,我更喜欢使用matchy的named_captures方法,该方法可以从ruby 1.9.1获得,安全操作符可以从ruby 2.3.0获得。

request.path.match(/\A\/(?<slug>(?!admin|assets)\w+)/)&.named_captures&.dig('slug')

#1


16  

Just use the ordinary (non-sugar) form.

只需使用普通(非糖)形式。

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

#2


2  

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

您可以发送任何方法,因此使用安全浏览操作符将是:

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

#3


2  

For better readability I would pick #dig instead of the #[].

为了更好的可读性,我会选择#dig而不是#[]。

Like,

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

instead of

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

#4


1  

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.

为了便于阅读,我更喜欢使用matchy的named_captures方法,该方法可以从ruby 1.9.1获得,安全操作符可以从ruby 2.3.0获得。

request.path.match(/\A\/(?<slug>(?!admin|assets)\w+)/)&.named_captures&.dig('slug')