Tutorial :What's the comma for in this code example?



Question:

cash = 100_000.00  sum = 0  cash += 1.00, sum while cash < 1_000_000.00 # underscores ignored  

I found the above example in a book "Learning Ruby" but using Ruby 1.9 it doesn't compile ("interpret"?)

syntax error, unexpected ',', expecting $end  

What's the comma supposed to be doing after 1.00?

Here's the full context of the example:

#Also, like if, you can use while as a statement modifier, at the end of a statement:  cash = 100_000.00  sum = 0  cash += 1.00, sum while cash < 1_000_000.00 # underscores ignored  #So cash just keeps adding up until it equals $1,000,000.00. I like that!  


Solution:1

It's an error. There's an unconfirmed error report about it, but nothing in the official errata (which haven't been updated since October 16, 2007).


Solution:2

it's most likely meant to be a semicolon, but the code would still be wrong. I feel like there is some context missing. What is the author doing with sum?

you can use while in the following way which may help explain the intent.

i = 0  puts i +=1 while i < 10  

Which means that this code would make sense

cash += 1.00 while cash < 1_000_000.00  


Solution:3

Well it wouldn't be the first nor the last programming book to have a glaring typo in the code.


Solution:4

Maybe it's a mistyped or misprinted semi-colon(;)?


Solution:5

The full context is as follows:

Also, like if, you can use while as a statement modifier, at the end of a statement:

cash = 100_000.00  sum = 0    cash += 1.00, sum while cash < 1_000_000.00 # underscores ignored  

So cash just keeps adding up until it equals $1,000,000.00. I like that!

There is obviously at least one mistake here. My guess is that the author accidentally used a perl or C style comma operator, then removed only part of the offending statement.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »