There isn’t much special about Ruby strings. Try the code snippets below in irb.
Construction
Strings can be created either using literals, or the new function.
1 2 3 4 5 6 7 8 9 |
|
Instance Functions
Like java.lang.String
, there are loads of predefined methods for the class. Remeber to refer to the Class documentation; there are code samples in there too. I’m just going to give you a taste of what’s available.
1 2 3 4 5 6 7 8 9 10 |
|
You’ll notice that the methods above only returns the result of the function. Some methods makes changes to the string in place. In general, the in place version will end with an exclamation mark, but note that this is not a standard.
1 2 3 4 5 6 7 8 |
|
Like Perl, Strings in Ruby are mutable. The object_id method I’m using below returns the id of the object, similar to the & operator in C. Strings inherit this from the Object class. Note that String objects are created every time a String literal is used.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Building a String
Strings can be built from variables in 4 different ways. The first two is probably the most commonly used
1 2 3 4 5 6 7 8 |
|
The third way is appending to strings. It’s more efficient in that it simply adds to a string instead of creating a new one, but it does change the string that is being appended to.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
The first line basically means, append “ + ” to e, then append f to e, then append “ is not equal to ” to e, and finally append g.to_s to e. I will demonstrate the final way when we get to the Arrays section.
Escaping characters
If the String you’re after is literally #{e} + #{f} is not equal to #{g}
, ie. you don’t want Ruby to evaluate e, f, and g, you can escape the #{}
blocks by prepending the # with a backslash \
. Alternatively, you can use single quotes instead of double quotes, and Ruby will escape those characters for you.
1 2 3 4 5 6 |
|
Ruby Documentation
There’s two way to access the API documentation, online through http://ruby-doc.org/, or offline in your command line with ri.
1 2 |
|
Unofficially, (if you don’t already) you’ll learn to love Google and Stack Overflow too :)