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
  • 相关阅读:
    准备开始学习XNA
    徐家骏:华为十年感悟
    memcached详解
    sql时间
    Sql server log file 缩小和删除
    看高手都是运用的灵活自如,打算从今天开始学习他!
    什么是内存对齐
    VS 2008 远程调试 与asp.net
    XNA入门的代码注释
    HTML的段落与文字
  • 原文地址:https://www.cnblogs.com/or2-/p/5564392.html
Copyright © 2011-2022 走看看