Strings in Ruby - Concatenating Strings
(Page 3 of 4 )
In Ruby, you can add on to an existing string with various concatenation techniques. With Ruby, you don’t have to jump through the hoops that you might if you were using a language with immutable strings.
Adjacent strings can be concatenated simply because that they are next to each other:
"Hello," " " "Matz" "!" # => "Hello, Matz!"
You can also use the+ method:
"Hello," + " " + "Matz" + "!" # => "Hello, Matz!"
You can even mix double and single quotes, as long as they are properly paired.
Another way to do this is with the<<method. You can add a single string:
"Hello, " << "Matz!" # => Hello, Matz!
Or you can chain them together with multiple calls to<<:
"Hello," << " " << "Matz" << "!" # => Hello, Matz!
An alternative to<<is theconcatmethod (which does not allow you to chain):
"Hello, ".concat "Matz!"
Or you can do it this way:
h = "Hello,"
m = "Matz!"
h.concat(m)
You can make a string immutable withObject’sfreezemethod:
greet = "Hello, Matz!"
greet.freeze
# try to append something
greet.concat("!") # => TypeError: can't modify frozen string
# is the object frozen?
greet.frozen? # => true
Next: Accessing Strings >>
More Ruby-on-Rails Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of Learning Ruby, written by Michael Fitzgerald (O'Reilly, 2007; ISBN: 0596529864). Check it out today at your favorite bookstore. Buy this book now.
|
|