Today I Learned

A Hashrocket project

How to conditionally add a value in array literals

I really like declarative things. It’s probably why I like React, and really dig functional programming approaches. So when I’m writing Ruby, sometimes I find myself wanting to delcare some array of values to use in a map, reduce, or each. The problem is, sometimes I only want a particular value give a condition. One pattern that I’ve started to try on for size is

def things
  [something, (something_else if reasons)]

Then, you can use it like so:

The conditional will evaluate and leave a nil in the array, which isn’t my favorite. However, I’ve found that this is a very useful pattern for simplifying certain methods.

Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.