热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

Icurrentlyhaveapieceofcodethatlookslike:我目前有一段代码如下:ifmatchrequest.path.match(\A\(?

I currently have a piece of code that looks like:

我目前有一段代码如下:

if match = request.path.match(/\A\/(?(?!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\/(?(?!admin|assets)\w+)/)&.[](:slug)

#2


2  

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

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

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

#3


2  

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

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

Like,

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

instead of

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

推荐阅读
author-avatar
月星名店_882
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有