Now that you have containers to hold values, you’ll want to do things with those values. Crystal offers the traditional mathematical operations, with a few variations depending on whether floats or integers are being processed. (You can mix floats and integers as well.)
| d = 10 + 2 # => 12 |
| e = 36 - 12 # => 24 |
| f = 7 * 8 # => 56 |
| g = 37 / 8 # => 4 (integer division) |
| h = 37 % 8 # => 5 (integers remainder / mod) |
| i = 36.0 / 8 # => 4.5 (float, or use fdiv function) |
Strings support the + operator for concatenation that is found in many programming languages.
| "this" + "is" + "a" + "test" # => thisisatest |
| "this " + "is " + "a " + "test" # => this is a test |
Concatenation works, but it’s a clumsy tool. The first item has to be a string for it to work at all, and it’ll break if you try to add a number, Ruby style. Fortunately, Crystal lets you assemble strings more naturally with interpolation.
| name = "Diamond" |
| hardness = 10 |
| "The hardness of #{name} is #{hardness}." # => The hardness of Diamond is 10. |
Crystal evaluates the value of any #{expression} syntax, converts it to a string if necessary, and combines it with the rest of the string.
Underneath these operators is a key truth of Crystal: all of these values are objects. Crystal maps common operator syntax to methods, making it easier for you to write readable code. The type corresponds to a class, which means that all of these values have methods you can use. For example, size is a method on String objects, which returns the number of characters as an Int32.
| name = "Diamond" |
| hardness = 10 |
| name.size # => 7 |
| hardness.size # => compilation error - undefined method 'size' for Int32 |
But size isn’t a method for Int32, so the compiler will give you an “undefined method ‘size’ on Int32” error.
➤ Try out and explain the output of the following statements in Crystal Playground:
| 12 + 12 |
| "12 + 12" |
| "12" + "12" |
| "I" * 5 |
| '12' + '12' |
| 5 * "I" |
| "12" + 12 |
| "2" * "5" |
18.218.187.108