difference between blank? present? empty?nil?in rails

Published on:

difference between blank? present? empty?nil?in rails

先来看 empty?这个instance method,

 [].empty?
 # => true.

 "".empty?
 # => true.

 "  ".empty?
 # => false

 nil.empty?
 # => Undefined method.

很明显,空值的实例变量会判定为 true,但如果有空格,会被判定为 false。

但在实际使用的过程中,我们常常需要判断一个字符串是否无内容,为了解决ruby 的这个问题, rails为 ruby 添加了一个 blank?方法。

[]. blank?
 # => true.

 "".blank?
 # => true.

 "    ".blank?
 # => true.

 false.blank?
 # => true

 nil.blank?
 # => true.

酱紫,就可以使用blank?来判断一个字符串或者数组是否内容为空。

[].present?
 # => false.

 nil.present?
 # => false.

 "".present?
 # => false.

 "  ".present?
 # => false.

 false.present?
 # => false.

除此之外,rails 还内置了一个present?方法,the opposite of blank?

# @return [true, false]

  def blank?
    respond_to?(:empty?) ? !!empty? : !self
  end

  # An object is present if it's not blank.

  #

  # @return [true, false]

  def present?
    !blank?
  end

还有一个方法跟以上三个方法有点像,叫 nil?

 nil. nil?
 # => true.

 [].nil?
 # => false.

 "".nil?
 # => false.

 "  ".nil?
 # => false.

Comments

comments powered by Disqus