Ruby 2 More on Strings

There are many methods in the String class (you don't have to memorize them all; you can look up the documentation) like the reverse that gives a backwards version of a string (reverse does not change the original string). length that tells us the number of characters (including spaces) in the string. upcase changes every lowercase letter to uppercase, and downcase changes every uppercase letter to lowercase. swapcase switches the case of every letter in the string, and finally, capitalize is just like downcase, except that it switches the first character to uppercase (if it is a letter), slice gives you a substring of a larger string.
The methods upcasedowncaseswapcase and capitalize have corresponding methods that modify a string in place rather than creating a new one: upcase!downcase!swapcase! and capitalize!. Assuming you don't need the original string, these methods will save memory, especially if the string is large.
We know that String literals are sequences of characters between single or double quotation marks. The difference between the two forms is the amount of processing Ruby does on the string while constructing the literal. In the single-quoted case, Ruby does very little. The backslash works to escape another backslash, so that the second backslash is not itself interpreted as an escape character. In single-quoted strings, a backslash is not special if the character that follows it is anything other than a quote or a backslash. For example 'a\b' and 'a\\b' are equal. In the double-quoted case, Ruby does more work. First, it looks for substitutions - sequences that start with a backslash character - and replaces them with some binary value. The second thing that Ruby does with double-quoted strings is expression interpolation. Within the string, the sequence #{expression} is replaced by the value of expression (referp013expint.rb). In this program, the value returned by a Ruby method is the value of the last expression evaluated, so we can get rid of the temporary variable (result) and the return statement altogether.
  1. # p013expint.rb  
  2. def say_goodnight(name)  
  3.   result = "Good night, #{name}"  
  4.   return result  
  5. end  
  6. puts say_goodnight('Satish')  
  7.   
  8. # modified program  
  9. def say_goodnight2(name)  
  10.   "Good night, #{name}"  
  11. end  
  12. puts say_goodnight2('Talim')  
It is to be noted that every time a string literal is used in an assignment or as a parameter, a new String object is created.
How is memory managed for Strings in Ruby? Is there a separate pool for Strings? Strings are objects of class String. The String class has more than 75 standard methods. If you refer to Ruby User's Guide, it says that "we do not have to consider the space occupied by a string. We are free from all memory management."

Listing all methods of a class or object

String.methods.sort
shows you a list of methods that the Class object String responds to.

String.instance_methods.sort
This method tells you all the instance methods that instances of String are endowed with.

String.instance_methods(false).sort
With this method, you can view a class's instance methods without those of the class's ancestors.

Comparing two strings for equality

Strings have several methods for testing equality. The most common one is == (double equals sign). Another equality-test instance method, String.eql?, tests two strings for identical content. It returns the same result as ==. A third instance method, String.equal?, tests whether two strings are the same object. An example p013strcmp.rbillustrates this:
  1. # p013strcmp.rb  
  2. # String#eql?, tests two strings for identical content.  
  3. # It returns the same result as ==  
  4. # String#equal?, tests whether two strings are the same object  
  5. s1 = 'Jonathan'  
  6. s2 = 'Jonathan'  
  7. s3 = s1  
  8. if s1 == s2  
  9.   puts 'Both Strings have identical content'  
  10. else  
  11.   puts 'Both Strings do not have identical content'  
  12. end  
  13. if s1.eql?(s2)  
  14.   puts 'Both Strings have identical content'  
  15. else  
  16.   puts 'Both Strings do not have identical content'  
  17. end  
  18. if s1.equal?(s2)  
  19.   puts 'Two Strings are identical objects'  
  20. else  
  21.   puts 'Two Strings are not identical objects'  
  22. end  
  23. if s1.equal?(s3)  
  24.   puts 'Two Strings are identical objects'  
  25. else  
  26.   puts 'Two Strings are not identical objects'  
  27. end  

Using %w

Sometimes creating arrays of words can be a pain, what with all the quotes and commas. Fortunately, Ruby has a shortcut: %w does just what we want.
  1. names1 = [ 'ann''richard''william''susan''pat' ]  
  2. puts names1[0] # ann  
  3. puts names1[3] # susan  
  4. # this is the same:  
  5. names2 = %w{  ann richard william susan pat }  
  6. puts names2[0] # ann  
  7. puts names2[3] # susan  

Character Set

A character set, or more specifically, a coded character set is a set of character symbols, each of which has a unique numerical ID, which is called the character's code point.
An example of a character set is the 128-character ASCII character set, which is mostly made up of the letters, numbers, and punctuation used in the English language. The most expansive character set in common use is the Universal Character Set (UCS), as defined in the Unicode standard, which contains over 1.1 million code points.
The letter A, for example, is assigned a magic number by the Unicode consortium which is written like this: U+0048. A string "Hello" which, in Unicode, corresponds to these five code points:
  1. U+0048 U+0065 U+006C U+006C U+006F  
Just a bunch of code points. Numbers, really. We haven't yet said anything about how to store this in memory. That's where encodings come in.

Character Encoding

UTF-8 can be used for storing your string of Unicode code points, those magic U+ numbers, in memory using 8 bit bytes. In UTF-8, every code point from 0-127 is stored in a single byte. Only code points 128 and above are stored using 2, 3, in fact, up to 6 bytes. This has the neat side effect that English text looks exactly the same in UTF-8 as it did in ASCII.
It does not make sense to have a string without knowing what encoding it uses. Thus, if you have a string, you have to know what encoding it is in or you cannot interpret it or display it to users correctly.
Ruby supports the idea of character encodings.

Encoding class

Objects of class Encoding each represent a different character encoding. The Encoding.list method returns a list of the built-in encodings.
Ruby has a way of setting the encoding on a file-by-file basis using a new magic comment. If the first line of a file is a comment (or the second line if the first line is a #! shebang line), Ruby scans it looking for the string coding:. If it finds it, Ruby then skips any spaces and looks for the (case-insensitive) name of an encoding. Thus, to specify that a source file is in UTF-8 encoding, you can write this:
  1. # coding: utf-8  
As Ruby is just scanning for coding:, you could also write the following:
  1. # encoding: utf-8  
Note: Ruby writes a byte sequence \xEF\xBB\xBF at the start of a source file, when you use utf-8.
If nothing overrides the setting, the default encoding for source is US-ASCII.
Here's some example code:
# encoding: utf-8
# λ is the Greek character Lambda here
puts "λ".length # => 1
puts "λ".bytesize # => 2
puts "λ".encoding # => UTF-8
view rawstring_encode.rb hosted with ❤ by GitHub