Ruby Strings

A string object in ruby can be created by using either double quotes, “Hello World”, or single quotes, ‘Hello World’. Both are objects which is a sequence of 8-bit bytes in memory belonging to the class String. Since this sequence of memory is used to represent characters of a spoken language: it is referred to as a string literal (the string literal is – Hello World and does not include the quotes).

string1

What’s the difference between ‘….’ and “….” ?

Single quotes allow for the simplest form string literal. It does not support substitution. It only supports two escape sequences ( \’ and \\ ). Double quotes on the other hand not only support substitution but also many escape sequences. Although this is not obvious from the string literal example above, if we try to create a string literal such as ‘My name is Suchitra and I’m learning ruby’ we can run into these limitations depending on how we implement it.

If we try to implement it just as above we can do so by escaping \’ in I’m and it works fine.

string2

However, if we want to insert the name as a variable, single quotes don’t support substitution but double quotes do.

string3

Additionally double quotes also support other escape sequences such as \” – Double quote, \\ – single backslash, \a – bell/alert, \b – backspace, \r – carriage return, \n – newline, \s – space, \t – tab.

With ruby strings, it is possible to perform certain string operations using what are usually arithmetic operators.

  1. Adding two strings (string concatenation) can be performed by using the + operator: puts ‘Sam, ‘ + ‘I am.’ Note however that, only a string can be added to another string. So if we try:  puts‘19’ + 75 we are told a number cannot be added to a string.
  2. The multiplication operator can be used where an object is required to be used repeatedly such as puts ‘etc.’*3 which would mean output the string etc. three times or output three sets of the string etc. But don’t expect 3*’etc.’ to work because we are asking for ‘etc.’ sets of 3 which is senseless.

string4

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s