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.99

  puts "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:

  • to_i a.k.a. to Integer
  • to_f a.k.a. to Float (the Ruby equivalent of a PHP Decimal)
  • to_h a.k.a. to Hash
  • to_a a.k.a. to Array