Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ternary operator based on if else

If i have following if else statement

if a.present? && b.value == 'N'
 b = test
elsif a.present? && b.value == 'Y'
 b = guest
end

I can write ternary operation for this

b = (a.present? && b.value == 'N') ? "test" : "guest"

but in this ternary oprator i am not looking for condition b.value == 'Y' and it could be something else 'd' or 'e'.

How do i update ternary operator so it verifies both conditions in if and elsif?

like image 406
User7354632781 Avatar asked Feb 04 '23 05:02

User7354632781


1 Answers

For something like this you might want to use a simple look-up table to eliminate some of the logic:

EQUIVALENT = {
  'Y' => 'guest',
  'N' => 'test'
}

if (a.present?)
  b = EQUIVALENT[b.value] || b
end

The || b part may not be necessary if non-mapped b values are ignored.

like image 190
tadman Avatar answered Feb 15 '23 12:02

tadman