April 5, 2016

Quick tour on how Ruby talks to the world

Consulting & Advisory Digital Transformation Ruby on Rails Development

A quick reminder about producing text messages in Ruby.

Talk to the world

The basic method for text output is puts from IO:

With interpolation it’s possible to insert some expression in a string:

For global, class and instance variables one can omit braces:

Strings can be concatenated via + or concat method:

But we can’t do the same with other types:

String’s + uses implicit type conversion using argument’s to_str method. So we can do the following patching and use numbers in concatenation:

So if one wants to use a custom class in similar expressions, to_str method needs to be added to the class.

Structured Talks

In a number of methods ruby follows some formatting conventions. printf prints the string to the output stream using format string, sprintf (aliased as format) puts the result of formatting in a returned string. string#% uses the same format string.

The format sequence used there allows developer to control numbers appearence (precision, numeral system) and alignment. It has the following syntax:


type defines the general output behavior for an argument (string, number or #inspect), flags regulate the options and width~/~precision set the corresponding appearns options. for the detailed description parameters see Kernel#sprintf documentation. Format string content which is not a format sequence is put as is.

Let’s print some aligned numbers. %10.2f stands for 10 position output, 2 digits after dot, right aligned (default):

Do the same but left aligned (- flag) and treat numbers as integers:

String#% method uses the same format sequence. Applying more than one argument to a format string requires an Array. Hash can be used for named parameters:

Delivering large messages

Large text also known as heredoc can be created the following way. Any identifier (instead of HEREDOC below) might be used:

Interpolation is allowed, but if you want to disable it put the heredoc identifier in a single quote:

Consulting & Advisory Digital Transformation Ruby on Rails Development

Latest Insights in Consulting & Advisory

The Rise of Kotlin – Moving Away from Java for Android Development

Kotlin is a programming language for the Java Virtual Machine that’s able to be used in any scenarios that currently…

Introducing our Sphere Heroes Program – Artem Korenev – Employee of the month

At Sphere, employee recognition is a key component of our corporate culture. We believe in celebrating the successes of our…

Write For Sphere

Are you a writer with tech expertise? Then we want to hear from you! Here are a few guidelines for…

View All Articles arrow

We are here to help:

checkmarkto become a customer checkmarkto become an investor checkmarkto send a media inquiry checkmarkto join our team checkmarkto simply say ‘hi’
Get in Touch