Here’s a quick tip: Use next
with an argument to return the value
early from an iterator.
(For the following examples, imagine much more complicated API logic than checking whether numbers are odd or even.)
We’re all used to next
to skip to the next item in the list:
[1, 2, 3, 4, 5, 6].map { |x|
next if x.even?
x**2
}
#=> [1, nil, 9, nil, 25, nil]
but what if you want to return the value? Typically, you would wrap your block in a conditional or use ternary:
[1, 2, 3, 4, 5, 6].map { |x|
if x.even?
x
else
x**2
end
}
#=> [1, 2, 9, 4, 25, 6]
Gross! Early returns (guard clauses) are all the rage, but how do you do
it in something like map
?
[1, 2, 3, 4, 5, 6].map { |x|
next(x) if x.even?
x**2
}
#=> [1, 2, 9, 4, 25, 6]
:boom: