简体   繁体   English

Ruby三元运算符(如果不是)

[英]Ruby ternary operator if else

How would you make this ternary? 您将如何进行三元处理?

if @user.skill.present?
    @skill = @user.skill
else
    @skill = Skill.new
end 
@skill = @user.skill || Skill.new

如果@ user.skill的值为零,它将把下一个值(Skill.new)分配给@skill。

I'd use: 我会用:

@skill = @user.skill.present? ? @user.skill : Skill.new

However, ternery statements aren't often an improvement in readability/maintainability. 但是,使用ternery语句通常不能提高可读性/可维护性。 They also don't improve processing speed. 它们也不会提高处理速度。 And they're frowned upon in some Ruby code shops and coding styles because they're too easily abused/misused. 而且它们在某些Ruby代码商店和编码样式中不受欢迎,因为它们很容易被滥用/滥用。

Using if / else is entirely appropriate in this case so don't be afraid to go that route. 在这种情况下,使用if / else完全合适,因此不要害怕走那条路线。 Consider this: If you write logic using a ternary operator, and need to add additional processing to a returned value, you'll have to switch to using regular if / else processing anyway, or you'll generate some horrible looking code that will reduce its readability. 考虑一下:如果您使用三元运算符编写逻辑,并且需要在返回的值中添加其他处理,则无论如何都必须切换到使用常规if / else处理,否则您将生成一些看起来很糟糕的代码,从而减少它的可读性。

你可以试试

@user.skill.present? ? @skill = @user.skill :  @skill = Skill.new
@skill = @user.skill.present? ? @user.skill : Skill.new

perhaps more readable as a two liner 也许更容易理解为两个衬里

@skill = @user.skill
if @skill.blank? @skill = Skill.new

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM