0

I was trying to write a small program in Ruby, and I ran into the following problem: Ruby doesn't seem to be able to group numbers in parentheses.

For example:

puts (2 - 0) / 10

# prints out 0

There is obviously a flaw in the logic here. What should be happening is that (2 - 0) gets evaluated first (according to the order of operations) and then (2 - 0) should get divided by 10.

Does grouping with parentheses in Ruby not work? By the way, I'm using 2.1.2.

GDP2
  • 1,948
  • 2
  • 22
  • 38

1 Answers1

2

You're doing integer division without realizing it. 2 / 10 does equal 0 in integer division.

Try instead running this:

puts (2 - 0) / 10.0

# prints out 0.2

You will probably get an answer more like what you're expecting. The reason is that by changing 10 to 10.0, you coerce the operation into floating point division.

user513951
  • 12,445
  • 7
  • 65
  • 82
  • Ah, I see what you're saying. I guess I forgot that there is a difference between integer division and float division :P – GDP2 Nov 07 '14 at 01:08