Abbey Workshop

Ruby: String Basics

This how to covers the basics of using and creating strings in Ruby. It covers how to create strings, combine strings, insert variable data into strings, and here documents. Very basic stuff, but vital if you are getting started with scripts.

Below is a short Ruby scripts that demonstrates the basic use of strings. Explainations of the code follows after the example.

strings.rb
   1:#!/usr/bin/ruby -w
   2:puts "Hello  World!\n"
   3:
   4:# Print a variable
   5:test = "human events"
   6:puts test
   7:
   8:# Combining or concatenating two strings
   9:puts "1: When in the course of " + test
  10:
  11:# Printing a value within a String. Interpolation like Perl
  12:puts "2: When in the course of #{test}"
  13:
  14:# Create a value using a here docment
  15:heredoc = <<END_OF_STRING
  16:-------------------------------
  17:Calling the test value again:
  18:#{test}
  19:End of the text
  20:-------------------------------
  21:END_OF_STRING
  22:
  23:puts heredoc
  24:

Download source for: strings.rb

Script Review

Here are some of the highlights.

  • Line 2 shows the basics of outputing a string. The puts statement is used to write a sting to standard output. If you run the script, you will notice that a carriage return is automatically added to the end of the string.
  • Line 5 shows how to assign a string to the variable test. Notice an extra carriage return has been added to the string. You use the same escape sequence '\n' that you would use in Perl or Java. However, instead of getting two carriage returns in the output you only get one. The string is output using the puts statement on line 6.
  • Line 9 shows one way to combine a string with a variable. The '+' sign can be used to concatenate two strings. In the example the two strings are combined and immediately output.
  • Line 12 shows a second way to combine strings by inserting the variable within a string. The #{...} sequence represents a variable expression in Ruby. This expression is evaluated and the result is returned as a string. In this case, just the contents of test are returned. We could get a lot fancier with the expression I'm sure, but let's keep it simple for now.
  • Finally, lines 15-23 shows the use of a here document. A here document allows you to put a number of lines of text into a variable and then output the contents just like any other string variable. Notice that the variable express can also be used in a here document the way it can be used in a regular one line string.

Well that covers the basic stuff. Additional string operators and ranges are covered in another HowTo.

Content Last Updated 10/2012

For more information, see the following books