Ruby Strings - Creation and Basics

From Techotopia
Revision as of 20:11, 27 October 2016 by Neil (Talk | contribs) (Text replacement - "<table border="0" cellspacing="0"> " to "<table border="0" cellspacing="0" width="100%">")

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
PreviousTable of ContentsNext
Looping with for and the Ruby Looping MethodsRuby String Concatenation and Comparison


Purchase and download the full PDF and ePub editions of this Ruby eBook for only $8.99


A string is a group of characters that typically make up human readable words or sentences. Because strings are essentially the mechanism by which applications communicate with their users it is inevitable that string manipulation is a key part of programming. In this chapter of Ruby Essentials we will cover the basics of working with strings in Ruby.


Contents


Creating Strings in Ruby

Strings are stored in Ruby using the String object. In addition to providing storage for strings, this object also contains a number of methods which can be used to manipulate strings.

A new string can be created using the new method of the String class:

myString = String.new
=> ""

The above method creates an empty string. Alternatively a new string may be created and initialized by passing through a string as an argument to the new method:

myString = String.new("This is my string. Get your own string")

Another option is to use the String method provided by the Kernel:

myString = String("This is also my string")

But, perhaps the easiest way to create a string is to simply assign a string to a variable name. Ruby then takes care of the rest for you:

myString = "This is also my string"

As far as creating string objects goes that is as easy as it gets!

Quoting Ruby Strings

Strings can be delimited using either double quotes (") or single quotes ('). Whilst both serve the purpose of encapsulating a string they have different purposes. The double quotes are designed to interpret escaped characters such as new lines and tabs so that they appear as actual new lines and tabs when the string is rendered for the user. Single quotes, however, display the actual escape sequence, for example displaying \n instead of a new line.

The following example demonstrates the double quote in action:

myString = "This is also my string.\nGet your own string"

puts myString
This is also my string.
Get your own string

As you can see, the \n was interpreted as a real new line causing our string to appear on two lines when printed.

The single quote gives us a different result:

myString = 'This is also my string.\nGet your own string'

puts myString
This is also my string.\nGet your own string

In this case the '\n' is treated literally as a '\' and an 'n' with no special meaning.


General Delimited Strings

Ruby allows you to define any character you want as a string delimiter simply by prefixing the desired character with a %. For example, we could use the ampersand to delimit our string:

myString = %&This is my String&

This enables us to avoid quotes and double quotes embedded in a string being interpreted as delimiters:

myString = %&This is "my" String&
puts myString
This is "my" String

It is also possible to define delimiter pairs such as parentheses, braces or square brackets:

myString = %(This is my String)
myString = %[This is my String]
myString = %{This is my String}

Ruby also provides a few special delimited strings. %Q is the equivalent of double quote delimiters and %q is the equivalent of single quotes. %x is the equivalent of back-quote (`) delimited strings.

An easy way to embed quotes in a Ruby string is to escape them by preceding them with a backslash (\):

myString = "This is \"my\" String"

myString = 'This is \'my\' String'

Another option, if you aren't using escape characters such as new lines (\n) is to use single quotes to delimit a string containing double quotes and vice versa:

myString = 'This is "my" String'

myString = "This is 'my' String"

Ruby Here Documents

A Here Document (or heredoc as it is more commonly referred to) provides a mechanism for creating free format strings, preserving special characters such as new lines and tabs.

A here document is created by preceding the text with << followed by the delimiter string you wish to use to mark the end of the text. The following example uses the string "DOC" as the delimiter:

myText = <<DOC
Please Detach and return this coupon with your payment.
Do not send cash or coins.

Please write your name and account number on the check and
make checks payable to:

        Acme Corporation

Thank you for your business.
DOC

When this string is printed it appears exactly as it was entered, together with all the new lines and tabs:

puts myText

Please Detach and return this coupon with your payment.
Do not send cash or coins.

Please write your name and account number on the check and
make checks payable to:

        Acme Corporation

Thank you for your business.

Getting Information about String Objects

The String object includes a number of methods that can be used to obtain information about the string. For example, we can find if a string is empty using the empty? method:

myString = ""
=> ""

myString.empty?
=> true

It is also possible to find the length of a string using the length and size methods:

myString = "Hello"

myString.length
=> 5


Purchase and download the full PDF and ePub editions of this Ruby eBook for only $8.99



PreviousTable of ContentsNext
Looping with for and the Ruby Looping MethodsRuby String Concatenation and Comparison