This post is for Ruby developers who need to conditionally add to an array: build a list that holds only the values whose conditions are true. It walks through six ways to build a golfer's statuses. With each one, it adds what Ruby's own documentation says about the methods that code calls: what each returns, whether it changes the array, and which values Ruby counts as false. Those documented return values are what each short version depends on.
The Grass Is Always Greener#
We're building a system to track a golfer's statuses during a tournament. This isa competitive tournament with people who are much better than I will ever be, soif a golfer is currently scoring under par, they're in contention to win. On this 18 hole course, if they've played the first nine holes, they've made the turn.Let's explore a number of ways we can build up an array that keeps track ofwhich, if any, of these statuses a particular golfer qualifies for. Not content to settle for one that works, we'll dig into a variety of options.
Teeing Up An Option#
We can start with an empty array, and explicitly add in any of the statuses thatthe golfer meets the conditions for.
def current_statuses
statuses = []
if under_par?
statuses << "in_contention"
end
if back_nine?
statuses << "past_the_turn"
end
statuses
endThere's nothing tremendously exciting here, and that's not a bad thing! It'sreasonably clear what this is doing.
Which methods add an element to a Ruby array?#
The first version has to conditionally add to an array, so it needs a method that adds an element and keeps the same array. Ruby's Array docs give <<, push, concat and + each its own entry, and the first three of them return self. The first version above uses <<, which the Array docs say "Appends object as the last element in self; returns self." The other methods differ in whether you get back the same array or a new one. The docs open by defining the class: "An Array object is an ordered, integer-indexed collection of objects, called elements". Each << puts the new status at the next index, so the statuses come back in the order the if statements ran.
| Method | What the Array docs say |
|---|---|
| << | "Appends object as the last element in self; returns self." An array passed in is added as one element. |
| push, alias append | "Appends each argument in objects to self; returns self." |
| concat | "Adds to self all elements from each array in other_arrays; returns self." |
| + | "Returns a new array containing all elements of self followed by all elements of other_array." |
Because << returns self, the first version can return statuses on its last line: each << added to that same array. The push entry also shows that it takes several arguments at once, so two statuses could go in with one call. To use them, start from an array literal such as statuses = [].
How do you use conditional statements to add to an array in Ruby?#
To conditionally add to an array, wrap the add in a conditional statement, as the first version does with its if blocks. Ruby's control expressions guide says "nil and false are false-values and true and any other object are true-values", so each push runs when its test returns anything but nil or false. The same guide documents shorter forms: modifier if, unless and the ternary operator.
The guide calls the block form, the one the first version uses, "a simple if statement" and spells out how Ruby runs it: "If the “test” expression evaluates to a true then the “then” expression is evaluated." The ternary operator is the short form of an if statement with an else branch. The guide says "You may also write a if-then-else expression using ? and :", and shows that its ternary "Is the same as this if expression". In a ternary, Ruby evaluates the test first, returns the expression after ? when the test is truthy, and returns the expression after : when it is falsy.
Modifier if and unless#
The guide says "if and unless can also be used to modify an expression." In that form, the statement to run sits on the left and the test sits on the right, as in the guide's own example a += 1 if a.zero?. So each if block in the first version could be one line, with the push on the left and its test, under_par? or back_nine?, on the right. The guide also says "The unless expression is the opposite of the if expression." The fifth version below uses unless for each removal.
The ternary operator#
The third version below puts a ternary inside the array literal. Ruby's literals guide says "You may place expressions inside the array", so each slot holds either a status or nil. The control expressions guide advises that "for readability it is recommended that the ternary if is only used for simple conditionals." It also says to "avoid using multiple ternary conditions in the same expression as this can be confusing."
Order matters when a ternary meets <<. Ruby's precedence table lists << above ? and :, and says "High precedence operations happen before low precedence operations." So statuses << under_par? ? "in_contention" : nil pushes true or false into statuses first, and the ternary applies to what the push returns. The third version avoids that, because each ternary sits in its own array slot.
Tapping It In#
We can make the prior suggestion a little more terse by using tap.
def current_statuses
[].tap do |statuses|
if under_par?
statuses << "in_contention"
end
if back_nine?
statuses << "past_the_turn"
end
end
endThis eliminates the need for the statuses temporary array from the priorsection.
What does tap return in Ruby?#
tap returns the object it was called on, which in the second version is the array the block fills. The Kernel docs for tap say it "Yields self to the block and then returns self." Whatever the block pushes into it is what current_statuses returns, so no variable has to be named on the last line.
Taking a Compact Swing#
We can also build our array to have an entry for each of the conditionals wehave, and removing the ones that aren't relevant.
def current_statuses
[
under_par? ? "in_contention" : nil,
back_nine? ? "past_the_turn" : nil,
].compact
endBy using compact,we'll remove any nil values, and we'll take advantage of that functionalityby explicitly adding nil if the golfer doesn't meet that condition.
Does compact remove false values?#
No, compact removes nil and nothing else, so false stays in the array. The Array docs say it "Returns a new array containing only the non-nil elements from self; element order is preserved." The docs' own example keeps 0, false, an empty string, an empty array and an empty hash. That is why the third version writes nil in the branch where a condition fails. compact also cleans up after map. The Array docs say map "can be used to create a new array based on the original array, but with the values modified by the supplied block". For example, [["in_contention", true], ["past_the_turn", false]].map { |status, ok| status if ok } returns ["in_contention", nil], so the status that fails leaves a nil in its place. Calling compact on that result returns ["in_contention"], and filter_map does both steps in one.
| Method | What the docs say |
|---|---|
| Array#compact | "Returns a new array containing only the non-nil elements from self" |
| Array#compact! | "Removes all nil elements from self; Returns self if any elements are removed, nil otherwise" |
| Hash#compact | "Returns a copy of self with all nil-valued entries removed" |
The bang version matters when calls are chained. If every condition in the third version passed, the array would hold no nil, and compact! would return nil instead of the array. The third version calls compact, which returns a new array either way. The Hash docs give hashes the same method for nil values.
Can you conditionally add to an array without compact?#
Yes, put a splat in front of each conditional slot, and a slot whose condition fails adds nothing, so no compact call is needed. When under_par? is false, "in_contention" if under_par? gives nil, and the splat of nil adds no element. The NilClass docs say nil.to_a "Returns an empty Array."
def current_statuses
[
*("in_contention" if under_par?),
*("past_the_turn" if back_nine?),
]
endA splat adds nothing for a nil slot or an empty array slot, but it keeps false: [*false] returns [false]. So write each status with if, which gives nil when the test fails. A ternary works the same way when its failing branch is nil or an empty array, as in *(under_par? ? "in_contention" : nil) or *(under_par? ? ["in_contention"] : []). The parentheses are optional for a ternary. A modifier if in the same spot needs them, and Ruby raises a syntax error without them. Either way, the nil slots never reach the final array.
Working On Your Backswing Takeaway#
Speaking of taking things away, we can also do the opposite of the first approach. We'll start by having each status, and then removing the ones thatdo not meet the necessary condition.
def current_statuses
statuses = ["in_contention", "past_the_turn"]
unless under_par?
statuses -= ["in_contention"]
end
unless back_nine?
statuses -= ["past_the_turn"]
end
statuses
endThis may be more helpful in situations where there are a lot more statuses, andonly a few of them may need to be removed for certain reasons. It may also helpwhen the full list of statuses persists on its own elsewhere, but then you alsoneed a subset of them in a particular case.
How do you remove elements from a Ruby array by value?#
Subtract another array with the minus operator, as the fifth version does. The Array docs say it "Returns a new array containing only those elements of self that are not found in other_array; the order from self is preserved." Elements are compared with eql?, and the docs' first example removes every copy of the matching value: subtracting [1] from [0, 1, 1, 2, 1, 1, 3, 1, 1] returns [0, 2, 3].
| Method | What the Array docs say |
|---|---|
| Array#- | "Returns a new array containing only those elements of self that are not found in other_array" |
| difference | "Returns a new array containing only those elements from self that are not found in any of the given other_arrays". Takes any number of other arrays. "Returns a copy of self if no arguments are given." |
| delete | "With no block given, removes from self each element ele such that ele == object; returns the last removed element" |
| reject | Removes by a block test: "returns a new array whose elements are all those from self for which the block returns false or nil" |
The fifth version writes statuses -= ["in_contention"]. Ruby's assignment guide calls this abbreviated assignment. Its example shows a += 2 and says "This is equivalent to" a = a + 2, and its list of operators that work this way includes the minus sign. Since the minus operator returns a new array, each -= points statuses at a new array. The delete method, by contrast, removes matching elements from self.
Selecting The Right Club#
Lastly, we'll put together a hash keyed on the statuses where the value is the result of the conditions. We can then flex some familiarity with Ruby's Enumerable module to pick out the applicable sections of the hash, returning only the statuses.
def current_statuses
{
"in_contention" => under_par?,
"past_the_turn" => back_nine?,
}.select { |_status, condition| condition }.keys
endSimilar to the prior suggestion, this may be helpful when you want to have thefull list of statuses and their associated conditions all compiled in one place,but then want to peel off which are relevant for a particular golfer at thistime.
How do Hash#select and keys build the array?#
Hash#select keeps the entries whose block returns a truthy value and hands back a new hash. Then keys returns those keys as a new array. The Hash docs say select "returns a new hash whose entries are those for which the block returns a truthy value." The keys entry says it "Returns a new array containing all keys in self."
The order of the result is set by the hash. The Hash docs say "A Hash object presents its entries in the order of their creation." So the statuses come out in the order the sixth version writes them: in_contention, then past_the_turn.
The select in the sixth version is Hash's own method. The Hash docs say the class "also includes methods from module Enumerable", and there select "returns an array of those elements for which the block returns a truthy value." Enumerable also has filter_map, which "Returns an array containing truthy elements returned by the block." The NEWS for Ruby 2.7.0 lists it: "Added Enumerable#filter_map." Its docs show it on a hash, returning each key whose value passes the block's test. That keeps the keys in one call, where the sixth version uses select and then keys.
Which approaches change the array in place?#
The first two versions change one array in place, and the other four build new ones. The documented return values show it. << and tap each return self. compact, the minus operator, Hash's select and keys each return a new array or hash. The table pairs each version in this post with the method it relies on and what the Ruby docs say that method returns.
| Version in this post | Method and what it returns |
|---|---|
| First: << in if blocks | <<: "returns self" |
| Second: tap | tap: "returns self", with << inside the block |
| Third: ternary and compact | compact: "Returns a new array" |
| Fourth: splat in the array literal | nil.to_a: "Returns an empty Array." The array literal builds a new array |
| Fifth: start full, subtract | Array#-: "Returns a new array", assigned back with -= |
| Sixth: hash, select, keys | select: "returns a new hash"; keys: "Returns a new array" |
Each quote comes from the method's entry in the Array, Kernel, NilClass and Hash docs.
Asking Help From The Caddie#
Here are some of the ways that we might solve this problem. What other wayscould we build this functionality? Let me knowwhat other approaches you would take.
Learn more about how The Gnar builds Ruby on Rails applications.


