Ruby (on Rails) methods — some specificities
Today I came across a correction and I was wondering: there are so many ruby (and rails) methods to verify the presence of something in a variable. What are the difference between all of them? We have .nil? .empty? .blank? .present?
When to use each one? where we call it and what those methods return? no idea. Then I resolve to search about it!
Let’s start with the differences between them:
.nil? -> used with any object and returns true if the object is nil
Things to know about .nil?
- all classes in ruby has access to this method
- nil reference to NilClass and it is a class with methods, then: nil =! empty/blank/nothing
- returns true in cases of objects are: non existent, invalid or explicitly set to nil
.empty? -> return true if the LENGTH of an array/string/hash is zero
Things to know about .empty?
- one blank space is not empty
- it is a method present just in array, string or hash classes
- return an ‘no method error’ when called in other class of objects
.blank? -> return true if the value of any object is blank/empty/nil
Things to know about .blank?
- more generic because it can be used in any object class
- returns true when the object is empty, nil or even if the object content is blank space
- returns true when it is called in a false object (FalseClass)
.present? -> it is the opposite of blank.
Things to know about .present?
- it is an rails method, not a ruby one.
- it is the same that not blank
- returns false for objects whose values are: nil, false, empty, or a white space string.
So, this is it! in fact the .present? and blank? methods are pretty useful because they covers more than the first two.