zoukankan      html  css  js  c++  java
  • .nil? .empty? .blank? .present? in Ruby on Rails

     1 We get confused when there are many options to choose from. Same is the case when it comes to use any one from the above list. But one needs to be careful in using them and it is better that we understand it well before using it.
     2 
     3 Let's see which method does what.
     4 
     5 .nil?
     6 
     7 - It is Ruby method
     8 - It can be used on any object and is true if the object is nil.
     9 - "Only the object nil responds true to nil?" - RailsAPI
    10 
    11 nil.nil? = true
    12 anthing_else.nil? = false
    13 a = nil
    14 a.nil? = true
    15 “”.nil = false
    16 
    17 .empty?
    18 
    19 - It is Ruby method
    20 - can be used on strings, arrays and hashes and returns true if:
    21 String length == 0
    22 Array length == 0
    23 Hash length == 0
    24 - Running .empty? on something that is nil will throw a NoMethodError
    25 
    26 "".empty = true
    27 " ".empty? = false
    28 
    29 
    30 .blank?
    31 
    32 - It is Rails method
    33 - operate on any object as well as work like .empty? on strings, arrays and hashes.
    34 
    35 nil.blank? = true 
    36 [].blank? = true 
    37 {}.blank? = true 
    38 "".blank? = true 
    39 5.blank? == false
    40 
    41 - It also evaluates true on strings which are non-empty but contain only whitespace:
    42 
    43 "  ".blank? == true"  ".empty? == false
    44 
    45 Quick tip: !obj.blank? == obj.present?
    46 
    47 activesupport/lib/active_support/core_ext/object/blank.rb, line 17 # (Ruby 1.9) 
    48 
    49 def present? 
    50  !blank?
    51 end
  • 相关阅读:
    常用MySQL函数连接
    spring boot和mybatis的多源配置亲测可用非常简单哦铁闸门
    RestTemplate请求发送post请求携带数组参数(亲测有效)
    idea配置tomcat
    前后端分离生成手机验证码
    前后端分离的图片验证保存及发送方式
    Java—大文件分片上传
    SpringAOP实战
    Spring Boot AOP的使用
    iOS开发日常记录
  • 原文地址:https://www.cnblogs.com/or2-/p/5564392.html
Copyright © 2011-2022 走看看