Reputation: 58883
I can use a ternary operator like this:
a.empty? ? a : b
If a
is just a short variable, this works. If I don't want to use a variable but, for example, I'm within a complex chain of array functions where i have no temp variables, how to this without having to repeat the chain? This seems to me to only work with nil values where I can use or
a.filter { bla bla bla }.map { bla bla bla }.reduce { bla bla } || b
But for any other kind of check how to do this?
a.filter { bla bla bla }.map { bla bla bla }.reduce { bla bla }.empty? ? a.filter { bla bla bla }.map { bla bla bla }.reduce { bla bla } : b
Upvotes: 3
Views: 161
Reputation: 79562
Use (or copy) presence
that active_support
defines exactly for this:
a.filter{ bla bla bla }
.map { bla bla bla }
.reduce{ bla bla }
.presence || b
Upvotes: 1
Reputation: 168101
This question has been asked repeatedly:
a
.filter{bla bla bla}
.map{bla bla bla}
.reduce{bla bla}
.tap{|a| break a.empty? ? a : b}
or, alternatively (which is not recommended):
a
.filter{bla bla bla}
.map{bla bla bla}
.reduce{bla bla}
.instance_eval{empty? ? self : b}
Upvotes: 4
Reputation: 5490
You can assign the value from the first part to a variable, then use it in the second part:
(temp = a.filter { bla bla bla }.map { bla bla bla }.reduce { bla bla }).empty? ? b : temp
Upvotes: 2