Precedence of operation in ruby
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 ignore开发者_如何学Cd?
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.
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
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.
精彩评论