User7354632781 User7354632781 - 3 months ago 10
Ruby Question

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

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?

Answer Source

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

  'Y' => 'guest',
  'N' => 'test'

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

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