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
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 to share
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 to share