Ruby math parenthesis wierdness

T

Tom Verbeure

All,

The code below:

m = 5*(
(1.0)
- (1.0/2.0)
)
puts m
m = 5*(
(1.0) - (1.0/2.0)
)
puts m

prints out:

bash-3.2$ ./run.rb
-2.5
2.5

The second result is what I expect, but I don't understand the first
result.

I usually put operands at the end of the line instead of the
beginning, so I never ran into this before, but this was originally
Python code that I converted into ruby.

Any insights?

Thanks,
Tom
 
G

Gregg Kang

I'm getting this type of issue too. It looks like any number you put
after the first paren '(' is ignored.

All these examples produce -20

m = 10*(123
-2)
puts m
 
M

Mikael Høilund

All,

The code below:

m =3D 5*(
(1.0)

This is the cause of the unexpected behavior. =46rom what I can see, =20
Ruby is interpreting the newline after (1.0) as a statement separator. =20=

Compare:

puts 5*(
(1.0);
- (1.0/2.0)
)

What's actually happening is that the third line (- (1.0/2.0)) is seen =20=

as a separate statement, not as a continuation on the second line. The =20=

minus sign in the beginning of the line is interpreted as the unary =20
negation operator, not the binary (as in relating to two numbers, not =20=

one) subtraction operator.

This works, however:

puts 5*(
(1.0) -
(1.0/2.0)
)

A quick irb session also illustrates my point:
?> 1.0/2.0

The fact that the last prompt is "?>", not ">>" is the key point here.

Hope this helps
Mikael H=F8ilund
 
D

Dave Bass

If you make the line continuations explicit by adding backslashes, Ruby
gives the correct answer:

irb(main):005:0> m = 5*( \
irb(main):006:1* (1.0) \
irb(main):007:1* - (1.0/2.0) \
irb(main):008:1* )
=> 2.5
 

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
474,202
Messages
2,571,057
Members
47,667
Latest member
DaniloB294

Latest Threads

Top