【问题标题】:Duplicating .blank? in standard Ruby复制.blank?在标准红宝石中
【发布时间】:2011-05-05 17:19:04
【问题描述】:

Rails 有一个 .blank?如果 Object 为空,则返回 true 的方法?还是没有?可以在here 找到实际代码。当我在 1.9.2 上尝试通过这样做来复制它时:

class Object

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

end

调用“”.blank?返回 true 但调用“”.blank?当根据rails documentation 时返回false,对于.blank,空白字符串应该评估为true?在我查看我最初编写的代码之前:

class Object

  def blank?
    !!self.empty? || !!self.nil?
  end

end

并得到相同的结果。我错过了什么?

【问题讨论】:

    标签: ruby


    【解决方案1】:

    你忘了这个 - https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/object/blank.rb#L95

    class String
      # A string is blank if it's empty or contains whitespaces only:
      #
      #   "".blank?                 # => true
      #   "   ".blank?              # => true
      #   " something here ".blank? # => false
      #
      def blank?
        self !~ /\S/
      end
    end
    

    【讨论】:

    • 谢谢!这就是我现在无法访问 grep 的结果。我会尽快将您标记为答案。
    【解决方案2】:

    String 类覆盖 Rails 实现中 blank?Object 实现:

    class String
    
      def blank?
        # Blank if this String is not composed of characters other than whitespace.
        self !~ /\S/ 
      end
    
    end
    

    【讨论】:

      【解决方案3】:

      如果字符串仅包含空格,则不会将其归类为 empty?

      >> "  ".empty?
      => false
      

      因此,您不妨也创建

      class String
        def blank?
          strip.empty?
        end
      end
      

      但请仔细考虑一下 - 像这样的猴子补丁是危险的,特别是如果其他模块会使用您的代码。

      【讨论】:

      • 将来会牢记这一点。现在我只是在学习更多关于 Ruby 和玩弄 .blank 的知识?在 IRB 中。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-30
      • 1970-01-01
      • 2011-04-26
      • 1970-01-01
      • 2019-08-09
      • 1970-01-01
      相关资源
      最近更新 更多