Ruby String Concatenation and Comparison

From Techotopia
Revision as of 20:45, 27 November 2007 by Neil (Talk | contribs) (New page: In the previous chapter (Ruby Strings - Creation and Basics) we looked at how to create a Ruby string object. In this chapter we will look at manipulating, comparing and concatenating...)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

In the previous chapter (Ruby Strings - Creation and Basics) we looked at how to create a Ruby string object. In this chapter we will look at manipulating, comparing and concatenating strings in Ruby.

Concatenating Strings in Ruby

If you've read any of the preceding chapters in this book you will have noticed that Ruby typically provides a number of different ways to achieve the same thing. Concatenating strings is certainly no exception to this rule.

Strings can be concatenated using the + method:

myString = "Welcome " + "to " + "Ruby!"
=> "Welcome to Ruby!"

In the interests of brevity, you can even omit the + signs:

 myString = "Welcome " "to " "Ruby!"
=> "Welcome to Ruby!"

If you aren't happy with the above options you can chain strings together using the << method:

myString = "Welcome " << "to " << "Ruby!"
=> "Welcome to Ruby!"

Still not enough choices for you. Well, how about using the concat method:

myString = "Welcome ".concat("to ").concat("Ruby!")
=> "Welcome to Ruby!"

Freezing a Ruby String

A string can be frozen after it has been created such that it cannot subsequently be altered. This is achieved using the freeze method of the String class:

myString = "Welcome " << "to " << "Ruby!"
=> "Welcome to Ruby!"

myString.freeze

myString << "hello"
TypeError: can't modify frozen string