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

Cop idea: redundant if-else statement #11945

Closed
ydakuka opened this issue Jun 12, 2023 · 2 comments · Fixed by #11951
Closed

Cop idea: redundant if-else statement #11945

ydakuka opened this issue Jun 12, 2023 · 2 comments · Fixed by #11951
Labels

Comments

@ydakuka
Copy link

ydakuka commented Jun 12, 2023

Is your feature request related to a problem? Please describe.

I have the code samples:

a1)

my_field =
  if condition?
    my_field
  else
    Time.now.utc
  end

my_field

a2)

my_field = condition? ? my_field : Time.now.utc

my_field

b1)

my_field =
  if condition?
    Time.now.utc
  else
    my_field
  end

my_field

b2)

my_field = condition? ? Time.now.utc : my_field

my_field

Rubocop has not detected any offenses.

ydakuka@yauhenid:~/Work/project$ bin/rails_docker rubocop example.rb
Inspecting 1 file
.

1 file inspected, no offenses detected

Describe the solution you'd like

I expected to have the following code samples:

a)

unless condition?
  my_field = Time.now.utc
end

my_field

b)

if condition?
  my_field = Time.now.utc
end

my_field
@l3x4
Copy link

l3x4 commented Jun 13, 2023

Maybe one-liner?

my_field = Time.now.utc if(unless) condition?

If the last my_field in your examples is an implicit return value, it can be also done like this:

def some_meth(my_field)
  return Time.now.utc if(unless) condition

  my_field
end

@vlad-pisanov
Copy link

I think that's what Style/RedundantSelfAssignmentBranch is for.

For example, this:

foo = cond? ? foo : bar

gets flagged with Style/RedundantSelfAssignmentBranch: Remove the self-assignment branch and is autocorrected to:

foo = bar unless cond?

However, if the branch is an expression, the cop doesn't detect it 🤔

foo = cond? ? foo : Time.now # no offense

@koic koic added the bug label Jun 14, 2023
koic added a commit to koic/rubocop that referenced this issue Jun 14, 2023
…gnmentBranch`

Fixes rubocop#11945.

This PR fixes a false negative for `Style/RedundantSelfAssignmentBranch`
when using method chaining or arguments in ternary branch.
koic added a commit that referenced this issue Jun 15, 2023
…dundant_self_assignment_branch

[Fix #11945] Fix a false negative for `Style/RedundantSelfAssignmentBranch`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants