`

Ruby的.nil? .empty? .blank? .present?区别

阅读更多

.nil? , .empty? .blank? .present?区别:

  • .nil? 和 .empty? 是ruby的方法。 .blank? 是rails的方法。

     

  • .nil? 判断对象是否存在(nil)。不存在的对象都是nil的。

     

  • .empty? 对象已经存在,判断是否为空字段,比如一个字符串是否为空串,或者一个数组中是否有值

     

  • .blank? 相当于同时满足 .nil? 和 .empty? 。railsAPI中的解释是如果对象是:false, empty, 空白字符. 比如说: "", " ", nil , [], 和{}都算是blank。 (object.blank? 相当于 object.nil?||object.empty?)。

     

  • present?方法就是blank?方法的相反,判断是否存在,因此present?方法与!blank?方法两者表达的意思是一样的。

 

 

例:.nil?

 


 

1
2
3
4
5
6
nil.nil?       => true
false.nil?     => false
1.nil?         => false
0.nil?         => false
"".nil?        => false
[].nil?        => false

 

例:.empty?

 

1
2
3
4
5
"".empty?          => true
"abc".empty?       => false
[].empty?          => true
[123].empty?   => false
1.empty?           => NoMethodError  #说明 empty? 方法不能用于整数

例:.blank?

1
2
3
4
5
6
7
8
9
10
11
true.blank?        FALSE
 false.blank?      TRUE
 "true".blank?     FALSE
 "".blank?         TRUE
 "\n".blank?       TRUE
 '\n'.blank?       FALSE
 'true'.blank?     FALSE
 ''.blank?         TRUE
 1.blank?          FALSE
 p [].blank?         TRUE
 p [1].blank?        FALSE

例:.present?

 

 

1
2
3
4
nil.present?       => false
[].present?        => false
"hello".present?   => true
["a"].present?     => true

 出处http://bohsu.blog.51cto.com/6966437/1324907

分享到:
评论

相关推荐

    true_string:将字符串转换为布尔值

    真字符串 可以转换为真值、 true和false的字符串集合。 "true" . truthy? "false" ....nil . falsy? 如果接收者分别为真或假,这些方法将返回true 。 安装 将此行添加到应用程序的 Gemfile 中: gem

    EasyUIImagePickerController

    strongSelf.presentViewController(imagePickerController, animated: true, completion: nil) } }, Fail: { //SVProgressHUD.showErrorWithStatus("无法获取照片权限") }) 选取图片来自相机 注意使用[weak ...

    Rails的邮件预览引擎MailsViewer.zip

    user_name: nil, password: nil, authentication: nil, enable_starttls_auto: true }, send_if: lambda { |mail| mail.destinations.select { |address| ["yedingding@gmail.com"].include?(address) }.any? ...

    es-query-builder:Ruby 中 Elasticsearch 的查询构建器

    Ruby 中 Elasticsearch 的查询构建器。 用法 gem 'es-query-builder' builder = EsQueryBuilder . new ( # Fields allowed searching with match query. query_fields : [ 'field1' ] , # Fields for ...

    is_bullshit:叫废话

    is_bullshit叫废话。... 以下值为合格的总废话: [nil, [], {}, 0, false, 'undefined', 'false', '', '0', 'nil', 'null'] .legit? 和.seems_legit? .bullshit?的对立是.bullshit? nil.bullshit?

    ipcat-ruby:client9ipcat的Ruby端口

    ipcat-ruby 库的ruby端口,用于对来自已知数据中心的IP地址进行分类 安装 使用捆绑器: # In Gemfile gem 'ipcat' 或与Ruby: gem install ipcat 用法 IPCat . datacenter? ( ip_address ) 如果ip_address来自...

    weak_attr_accessor:RubyMotion 的weak_attr_accessor

    #weak_attr_accessor 用于 ... @view_controller = nil else @view_controller = WeakRef . new ( obj ) end end end 安装 将此添加到您的Gemfile : gem 'weak_attr_accessor' 运行bundle install 执照

    in_business:用于检查给定的DateTime,Date或Time是否在预定义的开放时间范围内的gem

    在业务 处理业务开放时间非常困难,或者至少要为每个应用程序写很多工作。... # => nil (since we've not set any hours yet!) # We want to be open 9am til 6pm on a Monday InBusiness . hours . monday

    AutomaticCoder.zip

    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSDictionary *json = [data objectFromJSONData]; //init object Person *person = [[Person alloc] ...

    OptionalAPI:Swift Optional Monad 的可选扩展.​​.....是否使用它......它是可选的

    someOptional == nil ? True branch : False branch 新的: someOptional. isSome ? True branch : False branch someOptional. isNone ? True branch : False branch someOptional. isNotSome ? True branch : ...

    nil_or:执行除非 Nil

    gem 'nil_or' 然后执行: $ bundle 或者自己安装: $ gem install nil_or 用法 我什么时候需要它? 而不是写: date_of_birth = params [ :date_of_birth ] ? params [ :date_of_birth ] . to_date : nil ...

    Ruby菜鸟入门指南.md

    3. Ruby中"一切皆对象"的理念,数字、布尔值、类、nil等都是对象。 4. Ruby中"一切皆表达式"的设计,控制语句、方法定义等都会返回值。 5. Ruby中"一切皆方法调用",没有直接访问属性的方式,只有方法调用。 6. 变量...

    fluent-logger-ruby, 用于Fluentd的结构化记录器( ruby ).zip

    fluent-logger-ruby, 用于Fluentd的结构化记录器( ruby ) 录音机 结构化事件记录器示例简单require 'fluent-logger'log = Fluent::Logger::FluentLogger.new(nil, :host => 'localhost',

    macOS SwiftUI教程之通过回车或点击让TextField失去焦点

    macOS SwiftUI教程之通过回车或点击让TextField失去焦点。1、放弃焦点NSApp.keyWindow?.makeFirstResponder(nil)。2、异步调用DispatchQueue.main.async

    url_regex:提供用于验证或提取URL的最佳正则表达式

    网址正则表达式 提供最知名的正则表达式来验证和提取URL。 它基于和所做的出色工作。 为什么我们需要这个正则表达式的... UrlRegex.get(mode: :validation).match('https://www.google.com').nil? # => false UrlReg

    Container.rb:方便的 Ruby 对象容器,提供更清晰的视图

    方便的 Ruby 对象容器,提供更清晰的视图 安装 容器可用作 RubyGem: $ gem install container 基本用法:容器 容器同时充当数组和哈希 tags = Container . new tags << "Master" tags << "Disabled...

    Serialize-javascript.zip

     nil : null,  undef: undefined,  fn: function echo(arg) { return arg; },  re: /([^\s] )/g }); 标签:Serialize 分享 window._...

    nihilist:Nigilist Ruby gem —应用程序中用户模型的空对象

    它允许 null 对象为所有问题方法返回false ,为所有非 bang 方法返回nil为所有复数形式的方法(以及在 Ruby on Rails 中为同名 ActiveRecord 模型提供空关系)返回[] ,而无需定义它们。 安装 gem install nigilist...

    Golang2-new.docx

    4.2.11. nil slice和empty slice 69 4.2.12. For range 70 4.3. 结构 71 4.3.1. 什么是结构体? 71 4.3.2. 结构体声明 73 4.3.3. 结构体初始化 77 4.3.4. 嵌套结构体(Nested Structs) 81 4.3.5. 匿名字段 ...

    nii批量转mat和png

    nii批量转mat和png

Global site tag (gtag.js) - Google Analytics