Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - incorrect line break within statement still gives result?

The distilled script is the following:

z1 = (12 -
          2) / (5)
z2 = (12
        -  2) / (5)
puts(z1.to_s + " " + z2.to_s)

Which gives:

$ ruby rubytest.rb 
2 -1

Now, I'm aware that the z1 case is the right way to do it, because a hanging operator on the end of the line is interpreted as an automatic continuation of the line.

However, I would expect the interpreter to fail-fast on the z2 case, and tell me that the statement is incomplete, or that its second line is nonsensical. But it handles it "just fine" and gives the "-1" answer. Is it trying to appear confident by not admitting it's confused and hoping the bullshit answer will go unnoticed?

Could someone explain what is actually happening with the evaluation of z2, why is it "-1", why is there no syntax error, and is there an example where this behaviour is useful (or should we file a request to remove it)?

like image 395
Evgeni Sergeev Avatar asked Dec 13 '14 22:12

Evgeni Sergeev


1 Answers

It's a feature, but you might think it's a bug at first. It's for the same reason you are able to do this (which is handy many cases):

(call_function_1; call_function_2) if some_condition

A line feed is interpreted the same as ;. You will notice this evaluates fine for example, and only the last expression is returned, but all expression ARE evaluated none the less:

(1
 2
 3
 4
 5)
=> 5

It's the same as

(1; 2; 3; 4; 5)
=> 5

To see that all expressions are evaluated you can try this for example:

(puts "A"
 puts "B"
 puts "C"
 123)
A
B
C
=> 123

So your example becomes:

(12; -2) / 5

Which is the same as:

-2 / 5

Which is -1.

To make Ruby interpret 12 as an unfinished statement and not a separate statement you can tell Ruby this by adding a line continuation hint \:

(12 \
 - 2) / 5
=> 2
like image 180
Casper Avatar answered Nov 16 '22 02:11

Casper