Rails 3 - 重构 ruby 条件
我想知道是否有更简单的方法可以在 ruby 中执行这两个条件:
if params[:action] == 'index' || params[:action] == 'show'
并
if !(comment = (session[:my_params].include?(:comment) rescue nil)).nil?
提前致谢
I'd like to know if there is a simpler way to do these 2 conditions in ruby :
if params[:action] == 'index' || params[:action] == 'show'
and
if !(comment = (session[:my_params].include?(:comment) rescue nil)).nil?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于第一行,您可以这样做:
第二行实际上应该重构为两行:条件检查中的赋值是代码味道;从来没有理由。
如果您使用 Rails / ActiveSupport,则可以利用
Object#try
否则,您会遇到一些稍微笨拙的东西:
For the first one, you could do:
The second should really be re-factored into two lines: assignment within a condition check is a code smell; there's never a reason for it.
If you're using Rails / ActiveSupport, you can take advantage of
Object#try
Otherwise, you're left with something slightly clunkier:
1:
2:
第二个条件中的
!
和.nil?
是多余的但是,实际上,您不应该尝试使所有内容尽可能短,这是首先要关心的是你的代码对其他人来说有多清晰。第二个条件应该是这样的:
或者甚至
1:
2:
!
and.nil?
in second condition are redundantBut, really, you should not try to make everything as short as possible, the first thing to care about is how clear your code would be for other people. The second condition should look like:
or even
第一个可以像这样折射:
或
First one can be refractored like this:
or
这应该比使用数组和
include?
更快:第二个:
This should be faster than using an array and
include?
:The second one: