Chapter 3
Typing Variables and Controlling the Flow

Now that you know what Crystal looks like, and you’ve seen how the compiler behaves, it’s time to dig deeper into how Crystal uses types and how they affect the flow of your programs.

Programs manipulate data. That data comes in types, like integer, string, or array. In a dynamically typed language such as Ruby or Python, types are generally not specified in the code. At runtime, when the program executes, the environment determines the types of its data. Crystal rejects this model, largely because it lets errors surface while the program is running. Instead, Crystal compiles the program before it is run, and the compiler needs to know all the types. This lets the compiler signal many possible errors and generate much more optimized code. After the compiler has done its work, the program executes in a much safer and performant way.

However, you won’t see that many types written explicitly in Crystal code because the smart compiler can deduce many types. Occasionally, you have to specify the type to help the compiler, such as for the type of the contents of an array.

Crystal also supports more complicated scenarios. In some cases, the compiler concludes that a variable is supposed to contain data of more than one type: for example, sometimes a Boolean, sometimes an integer. Then its type is a union type, in this case a Bool | Int32.

In this chapter, we’ll dig deeper into types and control flow, and the exception handling that builds on them. To illustrate this, we’ll go over how to get input from the terminal. It’s not that fancy, but through it, you’ll start to get a feeling for how Crystal works.

You’ll also gain more experience using specific methods for manipulating strings, arrays, and hashes. The last two are generic types: they can hold elements of different types. Then you’ll use symbols, enums, and regular expressions and learn some nice tricks in advanced control flow. Throughout this and the following chapters, you’ll also start building on the currency converter project, applying many of the things you’ve learned.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.106.7