Chapter 4
Organizing Code in Methods and Procs

While you can write working code line by line without structuring it, you won’t usually get very far before you want to be able to reuse code and store logic in more sophisticated ways. Methods (sometimes called functions) let you group code into chunks, and you give them names so you can call them. In this chapter, you’ll see Crystal’s approach to methods. It’s very Ruby-like, though Crystal’s use of types creates some differences on the way to performant and readable code. If you feel the need, review Using Methods to get an introduction to methods.

Because everything is an object in Crystal, there are methods on everything, even simple values such as Int32 and Char. Operators such as / or <= are also methods. Everything we’ll talk about in this chapter also applies to the methods you’ll use in classes (see Chapter 5, Using Classes and Structs).

Luckily, much of what you know about methods in other languages applies here—we’ll review basics in this chapter, but it’s worth noting some things up front that may surprise you if you’re coming from other languages.

Methods in Crystal don’t have to live in a class, in contrast to Java or C#, for example. You can also define them (as we’ve seen many times in earlier chapters) at the top level of your program. It’s also common to group related methods in a module (see Using Modules as Namespaces) to be included in classes.

Crystal also has a strong sense of scope. Unlike Ruby or Python, Crystal doesn’t have global variables at all. Variables that you define locally inside a method won’t be visible outside that method. The inverse is also true in Crystal: variables that you define outside of a method won’t be visible inside that method, either.

 x = 1
 
 def​ ​add​(y)
  x + y ​# Error: undefined local variable or method 'x'
 end
 
 add(2)
..................Content has been hidden....................

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