Ruby三元运算符没有按预期返回

时间:2017-01-23 12:26:48

标签: ruby

我有以下代码

@services = []
@services << @user.services.where(active: true).blank? ? @user.services.build(active: true) : @user.services.where(active: true).first

我没有返回服务对象,而是在数组中得到true或false。那是为什么?

1 个答案:

答案 0 :(得分:3)

正如您在此precedence table中看到的那样,?高于(@services << @user.services.where(active: true).blank?) ? @user.services.build(active: true) : @user.services.where(active: true).first ,因此您的代码会被解析为:

@services = []
@services << (@user.services.where(active: true).blank? ? @user.services.build(active: true) : @user.services.where(active: true).first)

你可以写:

where

但它不易读,你打电话给active_services = @user.services.where(active: true) service = if active_services.blank? @user.services.build(active: true) else active_services.first end @services = [service] 两次。

@services = [@user.services.where(active: true).first || @user.services.build(active: true)]

更新来自@ mudasobwa的优秀评论:

@services = [@user.services.find_or_initialize_by(active: true)]

更新来自@Stefan,看起来您的代码相当于:

=IMAGE()