Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest way to write ternary in Ruby that returns other value for nil?

Often I want to write something that returns "Yes" if true, "No" if false, or "NA" (or any other string really) if nil. Currently I do this:

@contact.boolean ? 'Yes' : (@contact.boolean.nil? ? "NA" : "No")

Is this the shortest way to write this?

like image 200
Cooper Maruyama Avatar asked Nov 18 '25 06:11

Cooper Maruyama


1 Answers

Here's one idea:

> {true => "Yes", false => "No", nil => "N/A"}[true]
 => "Yes" 

So, of course, you would do {true => "Yes", false => "No", nil => "N/A"}[value]

like image 115
Jason Swett Avatar answered Nov 20 '25 20:11

Jason Swett



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!