User7354632781
User7354632781

Reputation: 2264

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?

Upvotes: 4

Views: 549

Answers (4)

Eric Duminil
Eric Duminil

Reputation: 54213

You can use a ternary operator. It doesn't mean you should do it, though:

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

Here's a small 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"

Upvotes: 1

tadman
tadman

Reputation: 211540

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.

Upvotes: 4

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 120990

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

This is the only DRY answer here so far.

Upvotes: 4

axiac
axiac

Reputation: 72177

I would not insist on the ternary operator but extract the common a.present? test in an outer if 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

To me, it seems much easier to read this way.

Upvotes: -1

Related Questions