Feature #8262

Confusing "undefined method" exception when using - operator on a string

Added by ajack (Jack Weeden) almost 4 years ago. Updated almost 4 years ago.

Target version:


When trying to use the minus operator (-) on a String, Ruby reports the following exception:

NoMethodError: undefined method `-@' for "5":String

I'm not sure if this is intended behaviour but it was confusing as it led me to believe I was trying to call -@"5" rather than -"5" (I realise the minus operator is invalid for a String but I was looking all over for somewhere I'd accidentally typed in an "@" symbol, rather than somewhere I was just trying to call -"5")

Applies to Ruby 1.8.7, 1.9.3 and 2.0.0


#1 [ruby-core:54240] Updated by marcandre (Marc-Andre Lafortune) almost 4 years ago

The thing is that the name of the "unary minus" method is "-@", and what you did was send that to "5".

42.send(:-@)  # => -42 
"5".send(:-@) # => same as -"5", i.e. NoMethodError: undefined method `-@' for "5":String

I agree it's not super clear, but it is correct and has the advantage of teaching people what the method for unary minus is, if they wanted to define one for example.

What would you have liked to read instead as an error message?

(moving to feature)

#2 Updated by marcandre (Marc-Andre Lafortune) almost 4 years ago

  • Tracker changed from Bug to Feature

#3 [ruby-core:54434] Updated by ajack (Jack Weeden) almost 4 years ago

OK, this makes perfect sense now! I'd never come across the "-@" syntax for unary operators. Thanks!

#4 [ruby-core:54435] Updated by marcandre (Marc-Andre Lafortune) almost 4 years ago

  • Status changed from Open to Closed

Perfect. I'll close this then, unless someone comes up with a better proposal.

Also available in: Atom PDF