【转】ruby中nil?, empty? and blank?的选择

后端开发   发布日期:2025年07月04日   浏览次数:114
  1. In Ruby, you check with nil? if an object is nil:
    article = nil
  2. article.nil? # => true

empty? checks if an element - like a string or an array f.e. - is empty:

  1. # Array
  2. [].empty? #=> true
  3. # String
  4. "".empty? #=> true

Rails adds the method blank? to the Object class:

An object is blank if it‘s false, empty, or a whitespace string. For example, "", " ", nil, [], and {} are blank.

This simplifies

  1. if !address.nil? && !address.empty?

to

  1. if !address.blank?



    .nil?

    - It is Ruby method
    - It can be used on any object and is true if the object is nil.
    - "Only the object nil responds true to nil?" - RailsAPI

    nil.nil? = true
    anthing_else.nil? = false
    a = nil
    a.nil? = true
    “”.nil = false

    .empty?

    - It is Ruby method
    - can be used on strings, arrays and hashes and returns true if:
  • String length == 0
  • Array length == 0
  • Hash length == 0

  1. Quick tip: !obj.blank? == obj.present?

    activesupport/lib/active_support/core_ext/object/blank.rb, line 17 # (Ruby 1.9)

    def present?
     !blank?
    end

以上就是【转】ruby中nil?, empty? and blank?的选择的详细内容,更多关于【转】ruby中nil?, empty? and blank?的选择的资料请关注九品源码其它相关文章!