A Crash Intro to Ruby Strings
by Itay Moav
|
This article will teach you, through code examples, how to
define and manipulate strings, about string operators and
also the Ruby approach to strings.
|
This crash tutorial is intended for programmers who are
familiar with OOP, The concept of Strings and have
successfully installed the Ruby interpreter and/or command
line tool.
This article covers the following:
- The ways to define a string
- Manipulating string characters
- String operators
- Putting expressions inside strings
The ways to define a string
Type the following lines in the command line tool, and see
the result. (# marks the start of a comment in Ruby).
I_am_a_string='Aren\'t or are we.\n Line?'
#Here I defined an Object of class String.
#with the value: [Aren\'t or are we.\n Line?]
puts I_am_a_string
#Here I outputted the value of I_am_a_string
#to the stdio. Notice you see the character [\n]
Strings objects created using a single quoted literal are
not being substituted except in the case of \' which is
displayed as ' and \\ which is displayed as \.
I_am_a_string="Aren't or are we.\n Line?"
#Here I defined an Object of class String.
#with the value: [Aren't or are we.\n Line?]
puts I_am_a_string
#Here I outputted the value of I_am_a_string
#to the stdio. Notice you don't see the
character [\n] but a new line.
When defining a String object using a " (double quotes), a
much greater substitution is done on the string literal.
Here is a short list of the most common control characters
and to what they are substituted when using double quotes.
- \a Bell/alert
- \b Backspace
- \e Escape
- \f Formfeed
- \n Newline
- \r Return
- \s Space
- \t Tab
- \v Vertical tab
- #{expr} Value of expr (More explanations on this one will follow).
Instead of defining a String using a single quote ' you can also
use the following syntax:
SimpleString=%q/a string literal/
puts SimpleString
#prints to the stdio [a string literal] The %q marks this as
a single quoted string, following by a delimiter.
#You must use the same delimiter at the start and end of
the string literal.
All the following examples are legal strings
puts %q(something (is it?) yes)
puts %q?am I a string?
puts %q[test test]
The same goes with double quotes. Use CAPITAL Q:
puts %Q(something (is\ait?) yes)
puts %Q?am\nI a string?
puts %Q[test\ttest]
A Crash Intro to Ruby Strings
HERE-DOC
|