PHP to Ruby

Learning Ruby through PHP examples

Casting to other Datatypes

May 6, 2018

Sometimes, we need to convert our data for a particular situation. The most common one I’ve come across in my years programming as a hobby and professionally is taking a price and putting it in text for the end user to read.

In PHP, we have scalar datatypes which include Booleans (the true or false things), Integers (whole numbers), Decimals (precise numbers), and Strings (the text guys).

So we use a special operation to convert between the different types. In PHP we call this transforming of data types casting:

$amount=19.99;echo'Your total comes out to $'.(string)$amount;=>'Your total comes out to $19.99'

The (string) keyword told PHP we want to convert $amount into a String from it’s natural Decimal form.

Things are done a little differently over in Ruby. Instead of global functions, remember Everything is an Object so we have public methods on all of the things.

So there are reserved methods on each of the basic Objects to convert one to the other:

amount=19.99puts"Your total comes out $#{amount.to_s}"=>'Your total comes out to $19.99'

So, the to_s method is just a shorthand for to_string. This same naming convention works across the basic Objects. The other common ones you’ll see are: