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
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}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With