了解红宝石代码行

时间:2013-07-26 17:48:57

标签: ruby-on-rails ruby

我正在研究无脂CRM的源代码。我试图了解其中一个app帮助程序中的这一特定代码行:

options[:selected] = (@account && @account.id) || 0

似乎是将带有键:selected的选项哈希值设置为实例变量@account0的值(如果@account不存在)。

&& @account.id在做什么?

4 个答案:

答案 0 :(得分:7)

确保@account不是假的,如果不是,则会将该选项设置为帐户的id。写得比较长,这相当于:

options[:selected] = if @account && @account.id
                       @account.id
                     else
                       0
                     end

或者

options[:selected] = (@account && @account.id) ? @account.id : 0

我可能会使用the andand gem,它看起来像这样:

options[:selected] = @account.andand.id || 0

答案 1 :(得分:0)

相当于写作,

options[:selected] = (@account != nil ? (@account.id != nil ? @account.id : 0) : 0)
然而,Ruby程序员更喜欢你在问题中指出的方式,因为你可以看到上面的代码真的不可读。此外,Ruby(以及其他动态编程语言,如JavaScript)具有truthy和falsy值的概念,允许用户编写简洁且更易读的代码。您可以在本文中阅读相关内容:A question of truth

答案 2 :(得分:0)

由于确保对象不是nil是一个非常常见的问题,因此在rails中有一种方法(但不是直接在ruby中):

options[:selected] = @account.try(:id) || 0
如果try(:id)nil@account,则

nil将返回false,并会在:id的任何其他地方致电@account案件。这也意味着如果对象不是nil或false并且没有响应id,它将引发错误。

答案 3 :(得分:0)

options[:selected] = (@account && @account.id) || 0

这行代码不会将options[:selected]设置为@account或0,而是将@account.id设置为0.原因是(@account && @account.id)将返回评估的最后一个语句,如果两者都是真的,那将是@account.id

正如其他人所说,(@account && @account.id)将首先验证@account是否确实存在;如果确实如此,由于短路,它会检查@account.id是否存在,并且如果确实存在options[:selected]则会设置@account。但是,如果{{1}}不存在,则该值将设置为0.

相关问题