Ternary operator based on if else

If I have an if else statement

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

      

I can write a ternary operation for this

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

      

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

How do I update a 3-D statement to check for both if and elsif?

+3


source to share


4 answers


For something like this, you can use a simple lookup table to remove some of the logic:

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

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

      



The part || b

may not be needed if not mapped values ​​are b

ignored.

+4


source


b = case b.value
    when 'N' then test
    when 'Y' then guest
    end if a.present?

      



This is the only DRY answer here.

+4


source


You can use the ternary operator. This does not mean that you should do this:

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

      

Here's a little test:

class Object
  def present?
    true
  end
end

class NilClass
  def present?
    false
  end
end

a = true

class B
  attr_accessor :value
end

b = B.new
b.value = 'Y'

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

p b
# "guest"

      

+1


source


I wouldn't insist on the ternary operator, but I would extract the normal tag a.present?

in the outer if

one and then write the rest of the code using if

modifiers
:

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

      

It seems to me much easier to read this path.

-1


source







All Articles