Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Get value if true or

Tags:

ruby

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
like image 291
pistacchio Avatar asked Dec 02 '25 02:12

pistacchio


2 Answers

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}
like image 188
sawa Avatar answered Dec 04 '25 16:12

sawa


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
like image 37
Reinstate Monica -- notmaynard Avatar answered Dec 04 '25 18:12

Reinstate Monica -- notmaynard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!