随笔 - 397  文章 - 3  评论 - 16  阅读 - 32万

.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
复制代码

 

posted on   c3tc3tc3t  阅读(217)  评论(0编辑  收藏  举报
编辑推荐:
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
阅读排行:
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示