除了这个Ruby惯用语之外,还有其他更好的选择吗? [英] Is there a better alternative to this Ruby idiom?

查看:60
本文介绍了除了这个Ruby惯用语之外,还有其他更好的选择吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己经常在控制器中编写以下代码:

I'm finding myself writing this bit of code in my controllers a lot:

params[:task][:completed_at] = Time.parse(params[:task][:completed_at]) if params[:task][:completed_at]

不要因为我每次都在改变我的意思而挂断电话.但是在很多情况下,我需要先检查params中的值并进行更改,然后再将其传递给 create update_attributes .

Don't get hung up on what I'm doing here specifically, because the reasons change every time; but there are many circumstances where I need to check for a value in params and change it before handing it off to create or update_attributes.

重复3次 params [:task] [:completed_at] 感觉很糟糕.有更好的方法吗?

Repeating params[:task][:completed_at] three times feels very bad. Is there a better way to do this?

推荐答案

一种略微缩短此方法的方法是:

One way to shorten this slightly is:

if c = params[:task][:completed_at]
  params[:task][:completed_at] = Time.parse(c)
end

或者,您可能更喜欢这样:

Or, you might prefer this:

params[:task][:completed_at] &&= Time.parse(params[:task][:completed_at])

在第二种情况下,仅在左侧为真"的情况下才会进行分配.

In the second case, the assignment will only happen if the left side is "truthy".

这篇关于除了这个Ruby惯用语之外,还有其他更好的选择吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆