tags:

views:

66

answers:

3

I am very new to Ruby, so please accept my apologies if this question is wierd

I tried puts 5-8.abs which returned -3, and then I tried puts (5-8).abs which returned 3.

What is happening exactly when I try puts 5-8.abs, it seems like abs is ignored?

+3  A: 

5-8.abs seems to be doing 5-(8.abs) = 5-8 = -3 like you got.

Also, any time precedence is the least bit up in the air, explicit parenthesization helps.

I82Much
Accepting the first answer, thank you !!!
Alphaneo
+4  A: 

Method call (8.abs in this case)always has higher Precedence than operators (- in this case).

So, 5-8.abs translats to 5-(8.abs) = 5 - 8 = -3

pierr
+8  A: 

It's a precedence issue. The method call, .abs, is evaluated before the minus operator.

5-8.abs # => equivalent to 5-(8.abs)

Think of it this way - whitespace is not significant in Ruby. What would you expect to happen if you saw this?

5 - 8.abs

Here's a reference for Ruby precedence rules.

Sarah Mei
Is - an operator? I was under the impression in ruby everything is a method.
johannes
Operators are special. They're evaluated differently (as you can see) and some of them can't be redefined (such as `=` and most of the logical operators). There's some useful stuff if you google "operator method ruby".
Sarah Mei