Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clarify when to use if-case returns #734

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1090,8 +1090,9 @@ Translations of the guide are available in the following languages:
```

* <a name="ternary-operator"></a>
Favor the ternary operator(`?:`) over `if/then/else/end` constructs.
It's more common and obviously more concise.
Favor the ternary operator(`?:`) over `if/then/else/end` constructs
for simple expressions. It's more common and obviously more
concise.
<sup>[[link](#ternary-operator)]</sup>

```ruby
Expand Down Expand Up @@ -1134,8 +1135,10 @@ Translations of the guide are available in the following languages:
```

* <a name="use-if-case-returns"></a>
Leverage the fact that `if` and `case` are expressions which return a
result.
When assigning a value that depends on a conditional, when
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with the premise, but not with the wording. This long sentence is very hard to process and should probably be broken down into 2-3 sentences.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems like this is really two rules:

(a) When doing an assignment that depends on a conditional, don't repeat the assignment statement in an if/then, use a conditional expression instead.

(b) When assigning a conditional expression, choose to use a ternary operator or an if/then expression based on the complexity of the expression.

I'm not sure the best way to accomplish that. I'd suggest restructuring the section to have two rules just like (a) and (b), but I'm assuming it's hard to change existing rules since Rubocop and others may use the anchor names. (No?)

the value expressions are too long to use a ternary expression,
leverage the fact that `if` and `case` are expressions which
return a result.
<sup>[[link](#use-if-case-returns)]</sup>

```ruby
Expand All @@ -1147,11 +1150,13 @@ Translations of the guide are available in the following languages:
end

# good
result = condition ? x : y

result =
if condition
x
complex.expression()
else
y
too.long(to: fit.in(a, ternary))
end
```

Expand Down