.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
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)