Project

General

Profile

Actions

Bug #19583

closed

Unary minus inconsistency when used with variables and literals

Added by hurricup (Alexandr Evstigneev) over 1 year ago. Updated over 1 year ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:113147]

Description

This feels a bit inconsistent and I could not find an explanation.

This is fine and - has higher precedence than .

-2.upto 0 do |arg|
puts arg
end

But this is not working, won't even compile (requires parens):

var = 2
-var.upto 0 do |arg|
puts arg
end

I presume that in the first example there is no unary minus operation, just negative literal.

Ok, according to this - my assumption is correct. The question is - why?

def some
  puts -2
  a = 42
  puts -a
end

puts RubyVM::InstructionSequence.of(method :some).disasm
Actions #1

Updated by hurricup (Alexandr Evstigneev) over 1 year ago

  • Description updated (diff)

Updated by Hanmac (Hans Mackowiak) over 1 year ago

-2 is a literal
- 2 is a function call of -@

and -@ doesn't have preference over function call, see this:

a = 2
v = -a.to_s
p v #=> 2

Updated by byroot (Jean Boussier) over 1 year ago

  • Status changed from Open to Closed

Yeah, I don't think this is a bug, and even if we decided another precedence would have been better, changing it would break way too much code.

Actions

Also available in: Atom PDF

Like0
Like0Like1Like0