String Handling

Before leaving the subject of strings, you’ll take a quick look at a few common string operations.

Concatenation

You can concatenate strings using << or + or just by placing a space between them. Here are three examples of string concatenation; in each case, s is assigned the string “Hello world”:

hello_world_concat.rb

s = "Hello " << "world"
s = "Hello " + "world"
s = "Hello "  "world"

Note that when you use the << method, you can append Fixnum integers (in the range 0 to 255), in which case those integers are converted to the character with that character code. Character codes 65 to 90 are converted to the uppercase characters A to Z, 97 to 122 are converted to the lowercase a to z, and other codes are converted to punctuation, special ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.