Reputation: 2210
In Rails I know to represent If-Else shorthand is this
if a==b
do_something(a)
else
do_something(b)
end
shorthand a==b ? do_something(a) : do_something(b)
How do I represent this in and if-elseif-else
statement?
if a==b
do_something(a)
elsif a==c
do_something(c)
else
do_something(b)
end
Upvotes: 1
Views: 2876
Reputation: 17480
It's not quite accurate to call that shorthand. That is the ternary operator, which represents a conditional. There is no elsif version.
As for making the code cleaner, if you have a lot of elsifs, a case statement will read better
case a
when b then do_something
...
end
And my personal favorite, wrap your conditional in a intent-revealing private method, or if it's complex enough, it's own object!
Upvotes: 0
Reputation: 150
you can try this:
(a == b) ? do_something(a) : (a == c) ? do_something(c) : do_something(b)
Or
(a == b) ? do_something(a) : ((a == c) ? do_something(c) : do_something(b))
Upvotes: 3