手把手教你学习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?

  

原文地址:https://www.cnblogs.com/SoulSpirit/p/3382220.html