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)]
end
Then, you can use it like so:
things.compact.map(&:cool_method)
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.