Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do newlines within parenthesis change arithmetic results?

Why do the following expressions resolve the way they do? Brackets should have higher precedence than newlines, shouldn't they?

3 - ( 1 + 1 )
# => 1

3 - ( 1
     + 1 )
# => 2

Omitting the plus also lets the expression evaluate to 2:

3 - ( 1
      1 )
# => 2

If I declare as a continuous newline (escaped) or move the plus to the first line, desired behavior is achieved:

3 - ( 1 \
     + 1 )
# => 1

3 - ( 1 +
      1 )
# => 1
like image 219
Felix Avatar asked Feb 29 '16 19:02

Felix


2 Answers

It is because Ruby recognizes a new line as an end of an expression unless the expression is incomplete. For example,

(1
+ 1)

is the same as

(1;
+1)

which is the same as +1 since the last expression within the parentheses is returned. And that is further the same as 1.

When you have a + at the end of a line, the expression is incomplete, and hence continues to the next line. That makes:

3 - ( 1 +
      1 )

to be interpreted as 3 - (1 + 1).

like image 132
sawa Avatar answered Oct 05 '22 03:10

sawa


If you have code in the brackets then every line will be threat as separated code line of code if you won't end it with \ or start new one with math operator.

So in your example:

def plus_minus_if_you_understand_this_the_problem_is_solved_i_guess 
    3 - (1
         1 )
end

Means I have number 3 and want to subtract expression in brackets. In the brackets I have line #1 number 1 and in #2 line number 1 again and as it's last line of expression it's retuned by Ruby (like in def last item before end is returned. So:

( 3   # doing nothing
  1 ) # returns 1

Also take a look bellow. Again, this part of code returns 2 as it is the last item in brackets:

( puts "hello!"
  2 ) => 2
like image 27
Jakub Avatar answered Oct 05 '22 01:10

Jakub