Replacements for the ternary operator

1,639 views
Skip to first unread message

J. Daniel Ashton

unread,
Oct 21, 2013, 9:39:25 AM10/21/13
to elixir-l...@googlegroups.com

Since the ternary operator was one of my favorite ways of DRYing up Java and Ruby, I find myself missing it in Elixir.  Here are the two alternatives I've seen so far:

    my_string = condition ? "value 1" : "value 2"    <--  In Ruby
    my_string = if condition, do: "value 1", else: "value 2"    <-- option #1 in Elixir
    my_string = condition && "value 1" || "value 2"    <-- option #2 in Elixir

Is this correct?  Are there better or other ways to get the same job done?

I see that someone else had suggested option #2 as an alternative in Ruby, here:

As far as I can tell, the two options should be the same unless "value 1" is meant to be false or nil.

Posting this here for discussion or for other noobs to stumble on when looking forlornly for the ?: operator.

With kind regards,

Daniel

Peter Minten

unread,
Oct 21, 2013, 9:48:42 AM10/21/13
to elixir-l...@googlegroups.com
Option #1 is what's usually done in Elixir. A ternary operator isn't
needed in languages that have sufficiently advanced macro's (or lazy
evaluation).

Granted, it looks a bit ugly, but it works quite well and makes logical
sense.

Jose Luis

unread,
Oct 22, 2013, 9:44:58 AM10/22/13
to elixir-l...@googlegroups.com
Hi.

I like the first option.

I'm a C++ programmer and I don't miss ternary operator in Elixir at all.

Everything is an expression. This is great, and this is what I miss in C++, Java, Python and other languages.


Reply all
Reply to author
Forward
0 new messages