zoukankan      html  css  js  c++  java
  • 手把手教你学习ROR-4.nil? empty? blank?的区别

    nil? empty? blank?的区别


    1nil?:

    check if it exists and that it is valid.In ruby,all classes inherit from the Object class.nil? is a method of Object.
    跟其他语言不同的是,其他语言会把nil当成是null,但是nil在ruby中指向的是一个class NilClass。所以nil.nil?=true

    cool_people = {:conan_the_destroyer => "man", :red_sonja => "woman"}
    
    cool_people[:george_bush_II]
    => nil
    cool_people[:george_bush_II].class
    => NilClass
    cool_people[:george_bush_II].nil?
    => true
    cool_people[:conan_the_destroyer].nil?
    => false
    
    test_var = nil
    test_var.nil?
    => true
    
    [].nil?
    => false
    
    "".nil?
    => false
    
    0.nil?
    => false
    
    false.nil?
    => false
    

      

    2empty?

    empty只用在一些Ruby Objects.String,Hash,Array。来判定当前的对象是否为空

    ["Larry", "Curly", "Moe"].empty?
    => false
    
    [""].empty?
    => false
    
    [].empty?
    => true
    
    {}.empty?
    => true
    
    "".empty?
    => true
    
    0.empty?
    => NoMethodError: undefined method `empty?' for 0:Fixnum
    
    test_var2 = nil
    test_var2.empty?
    = > NoMethodError: undefined method `empty?' for nil:NilClass
    

      

    3 blank?
    An object is blank if it‘s false, empty, or a whitespace string.
    是nil和empty的集合。

    dog = {:name => "Beauregard"}
    puts "What kind?" if dog[:breed].blank?
    => What kind?
    
    dog = {:name => "Beauregard", :breed => ""}
    puts "What kind?" if dog[:breed].blank?
    => What kind?
    

      

  • 相关阅读:
    [swustoj 1021] Submissions of online judge
    [swustoj 404] 最小代价树
    [swustoj 917] K-lucky-number
    [swustoj 183] 种树
    [LA 3887] Slim Span
    [ahu 1248] NBA Finals
    用js获取当前月份的天数
    WampServer
    jquery checkbox选中、改变状态、change和click事件
    为什么排版引擎解析 CSS 选择器时一定要从右往左解析?
  • 原文地址:https://www.cnblogs.com/SoulSpirit/p/3382220.html
Copyright © 2011-2022 走看看