Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Not Quite a String

The answer is that we tend to use strings of characters in our code for two rather different purposes: The first, and most obvious, use for strings is to hold some data that we are processing. Read in those Book objects from the database and you will very likely have your hands full of string data, things like the title of the book, the author's name, and the actual text.

The second way that we use strings of characters is to represent things in our programs, things like wanting to find all of the records in a table. The key thing about :all in our Book ActiveRecord example is that ActiveRecord can recognize it when it sees it—the code needs to know which records to return, and :all is the flag that says it should return every one. The nice thing about using something like :all for this kind of "stands for" duty is that it also makes sense to the humans: You are a lot more likely to recognize what :all means when you come across it than 0, or -1, or even (heaven forbid!) 0x29ef.

These two uses for strings of characters—for regular data processing tasks on the one hand and for internal, symbolic, marker-type jobs on the other—make very different demands on the objects. If you are processing data, you will want to have the whole range of string manipulation tools at your fingertips: You might want the first ten characters of the title, or you might want to get its length or see whether it matches some regular expression. On the other hand, if you are using some characters to stand for something in your code, you probably are not very interested in messing with the actual characters. Instead, in this second case you just need to know whether this thing is the flag that tells you to find all the records or just the first record. Mainly, when you want some characters to stand for something, you simply need to know if this is the same as that, quickly and reliably.

  • + Share This
  • 🔖 Save To Your Account