Line breaking in Ruby can be dangerous

S

Sky Yin

After programing in ruby for the past 3 months, I must say I'm
happier. However, I find where to break a long expression into lines
can be potentially dangerous and very hidden to debug. For example:
?> (1 * 2
?> + 1)
?> end
=3D> 1

I guess this may be attributed to the Ruby convention that the return
value by default is from the last line. The weird thing is that even
parentheses can't guarantee the result to be expected.

I'm still using 1.8.2 on win32. Is it a bug of that version?
 
F

Florian Frank

?> (1 * 2
?> + 1)
?> end
=> 1

I guess this may be attributed to the Ruby convention that the return
value by default is from the last line. The weird thing is that even
parentheses can't guarantee the result to be expected.

"1 * 2" and "+ 1" are both valid ruby expressions, the latter "(unary +)
1". How should Ruby find out, that you wanted to continue your first
expression in the next line?

If you want to avoid this, only break lines after operators, ",", etc.
like

1 * 2 +
1

You can also use

1 * 2\
+ 1

but I try to avoid this way, I think it's kind of ugly.
 
D

Daniel Schüle

I guess this may be attributed to the Ruby convention that the return
"1 * 2" and "+ 1" are both valid ruby expressions, the latter "(unary +)
1". How should Ruby find out, that you wanted to continue your first
expression in the next line?

because of (

I would also expect either a SyntaxError or correct result (3)

the latter seems more natural to me

Regards, Daniel
 
A

Adriano Ferreira

"1 * 2" and "+ 1" are both valid ruby expressions, the latter "(unary +)
1". How should Ruby find out, that you wanted to continue your first
expression in the next line?

Ruby would find it out because of the leading "(" or that would be
what I and apparently Sky Yin expect.

This works:
irb(main):001:0> (1
irb(main):002:1> )
=3D> 1

This too:
irb(main):003:0> begin (1
irb(main):004:2> ) end
=3D> 1

But I think I understand why it works this way. In Yin's example:

(1*2
+1)

is interpreted just like
(1*2;
+1)

what would not happen if he had written
(1*2+
1)

which gives a proper answer.

Kind regards,
Adriano.
 
S

Sky Yin

Thanks. When I first found it out, it's really a *big* surprise. This
actually took me quite a while to debug, cause the long expression
itself that I wrote simply looked nothing-wrong at the first glance.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top