Ruby (and Rails) have many ways to test whether something is … present. But each method behaves slightly differently, and some are Ruby-native while some are added by Rails. Here’s the summary, in case you don’t feel like reading the full details below: .nil? (Ruby) .empty? (Ruby) .blank? (Rails) .present? (Rails) true false NoMethodError […]
Ruby
Ruby’s safe navigation operator (&.)
Ruby’s safe navigation operator (&.) is a nil-safe way to chain operations. Let’s say we have a User class, and that class can have first_name and last_name attributes: Without safe navigation, we’d need a more-verbose if check to accomplish the same thing: If you’re familiar with Javascript, ruby’s safe navigation works just like javascript’s optional […]
Find elements in a ruby array
There are several ways to do this, and their outputs differ based on your needs Let’s do a couple of examples. Array.include? Simple: Array.index This method is a bit confusingly named. It gives you the first index at which the given element appears, not the element at the index given. Array.find and Array.detect Two names […]