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

New cop for .. operator precedence #4182

Closed
pocke opened this issue Mar 27, 2017 · 3 comments · Fixed by #9986
Closed

New cop for .. operator precedence #4182

pocke opened this issue Mar 27, 2017 · 3 comments · Fixed by #9986
Labels
feature request high priority A ticket considered important by RuboCop's Core Team

Comments

@pocke
Copy link
Collaborator

pocke commented Mar 27, 2017

The following code has a bug.

# test.rb
def foo(x = nil)
  x || 1..2
end

p foo
p foo(1..3)
$ ruby test.rb
1..2
test.rb:3:in `foo': bad value for range (ArgumentError)
	from test.rb:7:in `<main>'

The code is interpreted as (x || 1)..2, but it looks like x || (1..2) to me.
I think it is confusing, so, we need a cop for this problem. However we don't have the cop.

The cause is .. operator's precedence. https://ruby-doc.org/core-2.2.0/doc/syntax/precedence_rdoc.html


Expected behavior

x || 1..2

RuboCop adds an offence for the above code.

Actual behavior

The cop for this problem does not exist.

RuboCop version

$ rubocop -V
0.48.0 (using Parser 2.4.0.0, running on ruby 2.4.1 x86_64-linux)
@Drenmi
Copy link
Collaborator

Drenmi commented Apr 2, 2017

It can also be unexpected on the "other side" of the range:

1..2.to_a

will attempt to send #to_a to 2, rather than the range.

On that note, I think the cop should be a parenthesizing cop (possibly with an additional ambiguity cop.)

I've seen some code like this in RuboCop:

(foo.bar)..(baz.qux)

and we don't have any cops for enforcing a style. I also don't think there is a Style Guide entry. 🙂

@bbatsov
Copy link
Collaborator

bbatsov commented Apr 2, 2017 via email

@bbatsov bbatsov added the high priority A ticket considered important by RuboCop's Core Team label Sep 12, 2018
@denys281
Copy link
Contributor

denys281 commented Sep 2, 2019

@Drenmi is it actual issue?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature request high priority A ticket considered important by RuboCop's Core Team
Projects
None yet
4 participants