如何自定义if语句?

时间:2013-03-20 06:01:32

标签: ruby-on-rails ruby-on-rails-3

我想在@user.user_profile.prefecture.name if !@user.user_profile.prefecture.blank?为空时显示“未选中”。

如何自定义此代码?

控制器

@user.profile.prefecture.name if !@user.profile.prefecture.blank?

3 个答案:

答案 0 :(得分:3)

你可以使用三元运算符,它稍微冗长:

@user.profile.prefecture.blank? ? "Not selected" : @user.profile.prefecture.name

或者,如果prefecture实际上是nil / not-nil,那么摆脱blank?

@user.profile.prefecture ? @user.profile.prefecture.name : "Not selected"

最后,您可以使用try||稍微更加花哨,大多数熟练的Ruby开发人员会发现它们非常易读:

@user.profile.prefecture.try(:name) || "Not selected"

答案 1 :(得分:2)

喜欢这个

if @user.profile.prefecture.blank?
  'not selected'
else
  @user.profile.prefecture.name
end

答案 2 :(得分:-1)

更新:

1-如果对象为假,空或空白字符串

,则该对象为空

2-除非条件为假,否则执行语句代码

答案:

除非!@ user.profile.prefecture.blank?

,否则

“未选中”

解释:@ user.profile.prefecture.blank?每次@ user.profile.prefecture为false,为空时,或者为否定运算符将其转换为false的空白字符串,将返回true,因此可以执行除非代码部分。

这种方法对我来说非常“红润”,应该很容易理解。

相关问题