bk5115545
bk5115545

Reputation: 69

Inline if with else

I realize that it's not valid ruby but what would be the technical hurdles to implement the below functionality into the Ruby core language (of say v2.3)?

variable = 1 if condition else -1

I'd also like to allow the following for more generic use.

variable = { 1 } if condition else { -1 }

I'm very open to requiring an "end" at the end.

I get that a ternary can easily accomplish this but I'm looking for a more readable inline-if that allows an else.
I get that I can make a function which does this via any number of styles but I'd prefer to have it as readable as possible.

Thanks.

EDIT: I hate editing questions for obvious reasons. In response to the question of how the generic option is more ruby-esque, see the below example (I needed newlines).

variable = { 
  operation_one
  operation_two
  ...
  SUCCESS_STATUS_CODE
} if loaded_dependencies else { 
  do_detailed_logging
  FAILURE_STATUS_CODE
}

if variable then
  it_worked
else
  explain_why
end

Upvotes: 1

Views: 2284

Answers (1)

Because your example, while it seems readable to you, has too many ambiguities in other cases.

Not to mention that ruby has a way to do this, and it's the ternary operator. To say that your example is more ruby-like, is almost like wondering why the wheelbase of the Ford Mustang wasn't longer, and that it would be more "Mustang-like" if it was.

But here are some issues with your proposal, starting from your example:

variable = { 1 } if condition else { -1 }

Here you've given your "if else" bit a lower precedence than the "=".

In other words:

variable = ({ 1 } if condition else { -1 })

That's a serious problem, because it breaks the currently allowed:

variable = 1 if condition

The precedence for that statement is:

(variable = 1) if condition

And that's important. No assignment happens if the condition is false.

This can be a really big deal, for example if the lvalue (left side) actually has side-effects. For example:

var[0] = 1 if condition

The lookup for "var[0]" is a method in whatever class object var is, and while [] doesn't usually have side-effects, it can - and now you are going to do those side effects even if the condition is false.

And I won't even get into:

variable = { 1 } if condition if condition2 else { -1 }

But if you don't like it, you can always write your own language and see what happens!

Upvotes: 3

Related Questions