如果字符串为空则返回一些默认值 [英] If string is empty then return some default value

查看:57
本文介绍了如果字符串为空则返回一些默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常需要检查某个值是否为空并像这样写没有数据存在":

Often I need to check if some value is blank and write that "No data present" like that:

@user.address.blank? ? "We don't know user's address" : @user.address

当我们有大约 20-30 个字段需要以这种方式处理时,它就会变得丑陋.

And when we have got about 20-30 fields that we need to process this way it becomes ugly.

我所做的是使用 or 方法扩展 String 类

What I've made is extended String class with or method

class String
  def or(what)
    self.strip.blank? ? what : self
  end
end

@user.address.or("We don't know user's address")

现在看起来好多了.但还是很粗糙

Now it is looking better. But it is still raw and rough

如何更好地解决我的问题.也许最好扩展 ActiveSupport class 或使用辅助方法或 mixins 或其他任何东西.Ruby 的理念、您的经验和最佳实践可以告诉我什么.

How it would be better to solve my problem. Maybe it would be better to extend ActiveSupport class or use helper method or mixins or anything else. What ruby idealogy, your experience and best practices can tell to me.

推荐答案

ActiveSupport 添加了 如果present?(与blank?相反)和nil,则对所有返回其接收者的对象进行presence方法> 否则.

ActiveSupport adds a presence method to all objects that returns its receiver if present? (the opposite of blank?), and nil otherwise.

示例:

host = config[:host].presence || 'localhost'

这篇关于如果字符串为空则返回一些默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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