Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Different between .nil?, .empty?, .bank?, .present? and .any?

You can have basic definitions and examples for object checking in Ruby on Rails. It is necessary for a good RoR developer to have ability distinguishing these methods.

Different between .nil?, .empty?, .bank?, .present? and .any?

  1. 1. Difference between .nil?, .empty?, .bank?, .present? and .any? Ruby Syntax Tips Henry Le
  2. 2. .nil? It is a Ruby method. It can be used on any objects and will return true if the object is “null”.
  3. 3. .nil? examples nil.nil? = true ( “Only the object nil responds true to .nil?” – RailsAPI ) anthing_else.nil? = false
  4. 4. .empty? It is a Ruby method. Can be used on strings, arrays and hashes and will return true if their lengths are zero. Running .empty? on something that is nil will throw a NoMethodError.
  5. 5. .empty? examples [].empty? = true {}.empty? = true "".empty?= true " ".empty? = false nil.empty? => “NoMethodError: undefined method `empty?' for nil:NilClass"
  6. 6. .blank? It is a Rails method (in ActiveSupport). Operate on any object as well as work like .empty? on strings, arrays and hashes. It also evaluates true on strings which are non-empty but contain only whitespace.
  7. 7. .blank? examples nil.blank? = true " ".blank? = true "ntt".blank? = true [" “].blank? = false [nil].blank? = false
  8. 8. .present? It is a Rails method (in ActiveSupport). It is vice versa from .blank? !obj.blank? == obj.present?
  9. 9. .present? examples nil.present? = false false.present? = false true.present? = true [].present? = false [“"].present? = true [nil].present?
  10. 10. .any? Pass each elements of the collection to the given block the returns true if the block ever returns a value other than false or nil.
  11. 11. .any? examples [nil, false].any? = false We can customise the condition to return true: [nil, false].any? { |w| w == false } = true %w{ant bear cat}.any? { |word| word.length >= 3 } = true
  12. 12. .present? vs .any? [nil, false].present? = true [nil, false].any? = false
  13. 13. Conclusion

×