Using Methods

Variables and basic logic provide a foundation, but most code needs more structure than that. Crystal, like Ruby, provides methods as the primary unit of program structure. Methods have names, take arguments (typed arguments in Crystal’s case!), and return values. Free-floating methods are also called functions, but because Crystal mostly uses them in the context of objects and classes, you’ll mostly hear about methods.

You’ve already used a few methods—typeof, puts, and p are top-level methods, available anywhere. Some methods are specific to a particular context. The size method is available on strings, while each is on arrays. The methods you’ve used so far have been built into the core language and library, but you can create your own methods using syntax, def, and end, very much like Ruby’s.

 def​ ​double​(num)
  num * 2
 end
 
 puts double(6) ​# => 12

After the name of the method, the arguments are listed in parentheses. This method takes only one argument, but if there were multiple arguments, they would be separated with commas. Arguments are treated as variables within the scope of the method.

Note that a method returns the value of its last expression. The code could explicitly state returns num * 2, but it doesn’t have to.

The double method looks like it’s meant to work on numbers, with the multiplication operator, but it’s actually more flexible than that. Crystal strings also have a multiplication operator. double("6") will return 66. But double(true) will report in line 2: undefined method ’*’ for Bool.

If you want more control over how your functions respond to arguments of different types, you can specify the type explicitly:

 def​ ​double​(num : Int32)
  num * 2
 end
 
 puts double(6) ​# => 12

Now, if you try to double("6"), Crystal says no, returning a “no overload matches ‘double’ with type String” error. However, “overload” points to another opportunity. Crystal lets you overload methods, using the same method name with different numbers or types of arguments. If you want to provide different doublings for numbers and strings, you can:

 def​ ​double​(num : Int32)
  num * 2
 end
 
 def​ ​double​(str : String)
  str + ​" "​ + str
 end
 
 puts double(​"6"​) ​# => 6 6
 puts double(6) ​# => 12

While you can let Crystal infer types most of the time, there may be moments when you want to specify more precisely.

Your Turn 5

Write a method sample that returns an array with random floating point numbers. The size of the array is passed as an argument to sample. (Hint: Use rand to generate a random float number.)

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

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