ruby : nil?, empty? and blank?的选择
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了ruby : nil?, empty? and blank?的选择,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1442字,纯文字阅读大概需要3分钟。
内容图文
![ruby : nil?, empty? and blank?的选择](/upload/InfoBanner/zyjiaocheng/1156/b31480c4610d48179c2259993d73d5fb.jpg)
article = nil
article.nil? # => true
empty?
checks if an element - like a string or an array f.e. - is empty:
# Array
[].empty? #=> true
# String
"".empty? #=> true
Rails adds the method blank?
to the Object
class:
An object is blank if it‘s false, empty, or a whitespace string. For example, "", " ", nil, [], and {} are blank.
This simplifies
if !address.nil? && !address.empty?
to
if !address.blank?
.nil?
- It is Ruby method
- It can be used on any object and is true if the object is nil.
- "Only the object nil responds true to nil?" - RailsAPI
nil.nil? = true
anthing_else.nil? = false
a = nil
a.nil? = true
“”.nil = false
.empty?
- It is Ruby method
- can be used on strings, arrays and hashes and returns true if:
- String length == 0
- Array length == 0
- Hash length == 0
- Running .empty? on something that is nil will throw a NoMethodError
"".empty = true
" ".empty? = false
.blank?
- It is Rails method
- operate on any object as well as work like .empty? on strings, arrays and hashes.
nil.blank? = true
[].blank? = true
{}.blank? = true
"".blank? = true
5.blank? == false
- It also evaluates true on strings which are non-empty but contain only whitespace:
" ".blank? == true" ".empty? == false
Quick tip: !obj.blank? == obj.present?
activesupport/lib/active_support/core_ext/object/blank.rb, line 17 # (Ruby 1.9)
def present?
!blank?
end
原文:http://www.cnblogs.com/Fooo/p/4276785.html
内容总结
以上是互联网集市为您收集整理的ruby : nil?, empty? and blank?的选择全部内容,希望文章能够帮你解决ruby : nil?, empty? and blank?的选择所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。