PHP to Ruby

Learning Ruby through PHP examples

String Concatenation and Interpolation in Ruby

May 5, 2018

String Concatenation a.k.a. Adding to Strings

Adding to Strings to is one of the most basic but also some of the most valuable work to do in any program. You’ll need to manipulate text for users to read and also for your program to work under the hood.

In PHP it’s so common, we reserve the Period punctuation symbol . and devote to notate we’re gluing 2 strings together:

$champs='Cleveland Browns';echo'And the winners of the 2020 Superbowl are the '.$champs;=>'And the winners of the 2020 Superbowl are the Cleveland Browns'

Ruby agrees with this assumption. But unlike PHP where the + is only reserved for Math operations like you’d expect; Ruby also uses it for both Strings and Math:

champs='Cleveland Browns'puts'And the winners of the 2020 Superbowl are the '+champs=>'And the winners of the 2020 Superbowl are the Cleveland Browns'

Injecting Strings into Other Strings

A.k.a. String Interpolation, the act of injecting a String inside of another string. This is also a very common operation the day to day of any programmer.

In PHP, it’s not uncommon to see this practice:

$year='2020';$champs='Cleveland Browns';echo'And the winners of the '.$year.' Superbowl '.' are the '.$champs;=>'And the winners of the 2020 Superbowl are the Cleveland Browns'

However, this method of interpolation isn’t the most sightly experience. PHP offers another way of interpolation when you use double quotation marks:

$year='2020';$champs='Cleveland Browns';echo"And the winners of the $year Superbowl are the $champs";=>'And the winners of the 2020 Superbowl are the Cleveland Browns'

It accomplishes the same goal as the first example with considerably less mental gynmastics as the first example. However, I still find this method too easy to screw up for my liking.

sprintf will replace every %s with the given argument(s) to the function:

$year='2020';$champs='Cleveland Browns';echosprintf('And the winners of the %s Superbowl are the %s',$year,$champs);=>'And the winners of the 2020 Superbowl are the Cleveland Browns'

Whichever you prefer.

Ruby’s version of String interpolation is a bit of a hybrid approach:

year='2020'champs='Cleveland Browns'puts"And the winners of the #{year} Suberbowl are the #{champs}"=>'And the winners of the 2020 Superbowl are the Cleveland Browns'

Like PHP’s built in interpolation, you’ll need to wrap the String in double quotes " in order for Ruby to know to look for a special token. Since Ruby doesn’t have special characters in front of keywords for variables, it requires use to wrap our variable keywords with #{}.

With #{} Ruby can figure out how to replace that particular keyword with the variable’s contents.