All lessons

Working with Text

7 min · Ruby

Join strings, measure them, and embed values with interpolation.

Ruby · Working with Text0/5 cleared

Enemy 1 of 5

Joining strings with +

This code joins two strings with + and prints the result. Notice the space is already inside the first string, since + adds none. Press Run to see it.

Why this works

Ruby strings can be joined together with the + operator, the same symbol used for adding numbers. Ruby figures out which operation to perform based on the types of the values involved. + doesn't insert a space automatically, so if you want a gap between the joined pieces, you need to include it yourself, either as its own string or trailing/leading whitespace baked into one of the parts (notice the example's greeting already ends with ", ").

Unlike PHP's dedicated . concatenation operator, Ruby reuses + for both strings and numbers, but you can't mix the two directly. Trying to + a string and a number raises an error, since Ruby won't silently guess whether you meant to convert the number to text or the text to a number.

You
Packet Wolf
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.