1. Computing

Using Strings

By

Strings are what are known as first class objects. String literals have special syntax for creating strings easily. String values can be assigned to variables and the String class has a number of methods for querying and manipulating strings.

There are actually a few special syntaxes for creating String literals. The most common are the double quote and single quote. The difference between the two are the number of escape sequenced allowed. Single quoted String literals allow very few escape sequences (also called control sequences) and are safer to use with strings that have special characters. Double quoted String literals allow several types of escape sequences, as well as expression interpolation. Expression interpolation is a powerful feature that inserts the value of an expression into a string, allowing you to create strings based on the values of your variables. The following example demonstrates single and double quotes strings as well as some escape sequences and an example of variable interpolation.

#!/usr/bin/env ruby

s1 = 'Single quoted'
s2 = "Double quoted"
puts s1, s2

# s3 ends in an 'n' character,
# instead of a <a href="/od/mr/g/newline.htm">newline</a> character
s3 = 'No escape sequences\n'
s4 = "Escape sequences\n"
puts s3, s4

# s5 does not interpolate the #{}
# expression, s6 does
name = "Jim"
s5 = 'Hello #{name}'
s6 = "Hello #{name}"
puts s5, s6
  1. About.com
  2. Computing
  3. Ruby
  4. Beginning Ruby
  5. Using Strings

©2014 About.com. All rights reserved.