Data Types - PHP Vs Ruby (Part 2)

Ruby's types are actually objects with methods, which is different than PHP's primitive types. At first, I thought I'll have to do something like

age = Number.new(28)

Not so, in fact the number classes don't even have a new method. Declaring a value to be a number is:

age = 28;

I'm sure there's some fancy word to describe the magic that happens. I like automagically.

Numbers
Numbers in the range (normally−2^30 to 2^30−1 or −2^62 to 2^62−1) are objects class Fixnum, while numbers outside of that range are Bignum. Float, Fixnum and Bignum extend from a base class of Integer, which extends from class Numeric, which extends from Object (whew!). A nice feature of Ruby is a Fixnum will convert to Bignum when necessary and vice versa. More automagically action going on!

Side Note: I find a nice programmer friendly feature: You can use underscores in your numbers, such as 1_000_000 to help the reader to imagine commas there. Ruby doesn't care. I've seen this in Perl as well, but no such feature exists in PHP that I know of. Often when I write a large number in PHP, I'll put a comment with the number with commas. Helps me to make sure I have enough zeros and I can referrer to that comment later when reading the code. Obviously this only works if you remember to update your comment when you change the number.

Just for fun
Lets compare a few functions / methods. It might be hard at first to think of a number as an object:

absolute value of a anumber
Ruby: num.abs
PHP: abs($num);

Rounding up
Ruby: num.ceil
PHP: ceil($num);

Rounding Down
Ruby: num.floor
PHP: ceil($floor);

Round (the kind we learned in school!)
Ruby: num.round()
PHP: round($num, 2); // round to second decimal place

In Ruby, I don't see a place where the number of digits to round to is specified like the php function. Any ideas? Example: If you were trying to round a dollar amount up to the nearest penny, I suppose you could multiply by 100, round, then divide by 100.

You can easily convert between types with the methods
to_s - convert to string
to_i - convert to fixnum (or bignum if necessary)
to_f - convert to float

For working with numbers with large decimals, you can use the BigDecimal library class. You'll have to include this library before using.

Yeah yeah yeah…
The point of all this was to figure out, does Ruby "handle" types the same as PHP? Aside from them being objects, I've decided it was yes. You can assign a var "num" a string, then assign it an integer and it doesn't care. This was the point my friend was making, which is one of his beefs with PHP and Perl... and now Ruby. When he asked me if this was so in Ruby, I hesitated. I thought that perhaps since they were objects it might not let you assign a different type. I guess it was just a wild hope, but I suppose it takes a lot of processing on the code compiler to check types while assigning!

Thanks Doug

Never heard of the term "Duck Typing" thanks for the pointers!