Changes

Jump to: navigation, search

Ruby String Concatenation and Comparison

1,422 bytes added, 20:45, 27 November 2007
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...
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:

<pre>
myString = "Welcome " + "to " + "Ruby!"
=> "Welcome to Ruby!"
</pre>

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

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

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

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

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

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

== 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:

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

myString.freeze

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

Navigation menu