pistacchio
pistacchio

Reputation: 58883

Ruby: Get value if true or

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

Answers (3)

Marc-André Lafortune
Marc-André Lafortune

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

sawa
sawa

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

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

Related Questions