Chapter 3.1 Strings

Strings are sequences of bytes that represent a sequence of characters. A string literal is the most common form of string. It is a constant string which is created by enclosing it in single or double quotes.

Example:

puts 'Hi, John.' --> Hi, John.

puts 'What\'s going on?' --> What's going on?

A backslash symbolizes an escape sequence and is followed by a character to create normally unprintable characters.

A single quote contains a limited set of escape sequence. Double quotes offer more escape sequences and expression interpolation. The following table lists the escape sequences:

escapeseq.png

Expression interpolation allows you to insert value of pieces of Ruby code into strings directly.

Everything in Ruby is an object.

Example:

Input: "inches/yard: #{12*3}"  
Output: inches/yard: 36

Input:"#{"Ruby! "*3}" 
Output: Ruby! Ruby! Ruby!

Special delimiter %Q and %q also allow you to create strings. To use the delimiter, type %Q and %q followed by any non-alphanumeric, non-multibyte character.

Example:

Input: %q{Starbucks and Coffee.} 
Output: Starbucks and Coffee.

Input: %Q; #{"Ice cream! "*4};
Output: Ice cream! Ice cream! Ice cream! Ice cream!

%q acts like the single quoted string. %Q acts like the double quoted string.

Heredocs is another way to create to strings in Ruby. To create a string using heredocs, specify a delimiter after a set of << characters to start the string and putting the delimiter on a line of its own to end it.

Example:

my_string = << MY_STRING

MY_STRING

The to_s method of an object can also be used to create a string instance.


  • Currently 2.98/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
  Flag Inappropriate Content 0 comments