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).
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.
However, if we want to insert the name as a variable, single quotes don’t support substitution but double quotes do.
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.
- 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.
- 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.