Ruby String object of class String explained
Ruby strings are similar to string in other language such as Python, Pearl, C and others. They are mutable, flexible and dynamic. Declaring Ruby string is simple as
my-string = “My Example String”
In the example above, my-string is an object and belongs to class String. As a result, Ruby strings have methods exposing various properties of the string. For instance, my-string.length or my-string.length() will both display number of characters in the Ruby string. Please note, parenthesis are optional and often times omitted by Ruby developers.
In addition, you can always call additional methods on top of String class methods such as my-string.length.next, which will give you an increment by one of the my-string length.
It is important to note that Ruby string Class handles non-ASCII characters different from other languages. For example, French string était has 5 characters but Ruby interprets é as two characters. It is doing it because accented e has two bites in it and Ruby interprets string length by the number of bytes.
There is another way of initializing string with multiple lines and paragraph using <<EOF and #=> notation.
long_string = <<EOF
line 1
line2
#=>
Ruby strings can be cut into substring by using slicing in the following way my-string.slice(2,7). In addition, Ruby allows to slice bytes of the string using my-string.byteslice(3) method.
Ruby strings are mutable as mentioned prior which makes them changeable after declaration. In order to change an existing string you’ll need to use an exclamation point (!) at the end of the method of the string. Example: my-string.upcase! will update existing string without creating a new instance.
Ruby has another syntactical predicate that returns a true/false value and it is done by adding a question mark at the end. Example: my-string.empty? or my-string.include? ‘letter’
Ruby follows Matz’s design principles which stipulates that Ruby is designed for humans not computers.
Note that Ruby stores a string as a sequence of bytes. Some of the popular methods for String class are
s = “my string to modify”
s.upcase
s.downcase
s.swapcase
s.capitalize
s.strip
s.center
s.ljust
s.rjust