The Saga Continues: Language tidbits in Ruby Vs. PHP

I wrote a simple math quiz game in Ruby, its one of the first things I wrote as a kid when I was learning GW-Basic (sigh, those were the days!). I found a few surprising differences in Ruby that I'm used to in PHP. Here are a few tidbits I discovered.

Increment Operators
You know these, its what you have in every for statement and quite often used in other looping structures. It PHP its used like $var++ and $var-- … which as we know, is to increase the value in the variable by one or subtract by one respectively. Well to my surprise (and failed Ruby code when I tried it) they aren't in Ruby. You have to use var += 1 and var -= 1 . weird huh? I wonder if this will change in future versions of Ruby. It's not THAT big of a deal, but I was surprised. I suppose it makes it easier later when you want to increase by 2 or 3. But, having a standard way to only increase by ONE is a good idea as a check against the programmer. What if they accidentally hit the 2 or 3 instead of a 1?

Data Types
Another thing I found different is types. PHP does on the fly type casting, so if I have two string "5" and "3" and I try to add them, it will convert them to integers and add them together giving me "8" … not so with Ruby. I had to use the "to_i" method to convert the number to an integer first. So "8".to_i + "5".to_i would convert both numbers to integers and do the math. This sort of thing has always bugged me about php.

Iterative Loops
I wanted to do my quiz for 10 problems. So I wanted to use a for loop. In php it would look like this:

for ($x = 1; $x <= 10; $x++) {


However, in Ruby we have something totally different.

1.upto(10) do |x|


It is certainly less typing, though still a big foreign to my brain where in all the languages I've ever done, the for loop has been written just about the same as in php. According to the docs this type of statement helps to avoid off by one errors. I can see that, you specify the start and end and Ruby takes care of the rest. You don't have to specify and increase the counter variables. I know there has been times when I have forgotten or typo'ed something in the "for" statement in php (DOH!).

If I misunderstood something, clue me in.

A standard way to increase

A standard way to increase by 1:

a = 5 # => 6 # => 6
a.succ # => 6
5.succ # => 6

The reason that it doesn't have a ++ operator is because it can end up not making sense. For example, in the above the "5" is a Fixnum object of value 5, and the "a" variable is also a Fixnum value of "5".

But you can't do this:


Because then all of a sudden 5 would equal 6.

Does that make sense?

ahh I see

Thanks. Thats kinda cool, I hadn't seen that method yet. :)

Thanks for the tip

Thanks, I hadn't seen that anywhere yet. :)

That looks right

you can do

var += 5

to increase the variable by 5 instead of 1.