Programming Crystal by Ivo Balbaert & Simon St. Laurent
Author:Ivo Balbaert & Simon St. Laurent [Balbaert, Ivo]
Language: eng
Format: azw3
Tags: Pragmatic Bookshelf
Publisher: Pragmatic Bookshelf
Published: 2019-01-30T00:00:00+00:00
Structuring a Class
In the previous section, and in âOrganizing Code in Classes and Modulesâ, you saw a simple Mineral class. Hereâs the class code by itself without any additional logic:
â âclassâ Mineral
â getter name : String
â getter hardness : Float64
â getter crystal_struct : String
â
â âdefâ âinitializeâ(@name, @hardness, @crystal_struct) â# constructorâ
â âendâ
â âendâ
This class has three read-only instance variables: name, hardness, and crystal_struct. Giving them a type is imposed by the Crystal compiler. But you can also do this in the initialize method:
classes_and_structs/classes.cr
â âclassâ Mineral
â getter name, hardness, crystal_struct
â
â âdefâ âinitializeâ(@name : String,
â @hardness : Float64,
â @crystal_struct : String)
â âendâ
â âendâ
Default values can be assigned like this:
â âdefâ âinitializeâ(@name : String = â"unknown"â, ...)
â âendâ
Some people use symbols like :hardness for the property name, but it isnât required. A property without a type must have a default value. Or you could give it a value in initialize (try it!). You donât need to define variables at the start of the class.
The new method creates a Mineral object:
â min1 = Mineral.ânewâ(â"gold"â, 1.0, â"cubic"â)
â min1 â# => #<Mineral:0x271cf00 @crystal_struct="cubic",â
â â# => @hardness=1.0, @name="gold">â
â min1.âobject_idâ â# => 41012992 == 0x271cf00â
â typeof(min1) â# => Mineral # compile-time typeâ
â min1.âclassâ â# => Mineral # run-time typeâ
â Mineral.âclassâ â# => Class # all classes have type Classâ
new is a class method thatâs created automatically for every class. It allocates memory, calls initialize, and then returns the newly created object. An object is created on the heap and it has an object_id: its memory address. When it gets a new name or when itâs passed to a method, only the reference is passed. This means the object is changed when itâs changed in the method.
When youâre not sure which types your initialize method will accept, you can also use generic types like T, as in this class Mineralg:
classes_and_structs/classes.cr
â âclassâ Mineralg(T)
â getter name
â
â âdefâ âinitializeâ(@name : T)
â âendâ
â âendâ
â
â min = Mineralg.ânewâ(â"gold"â)
â min2 = Mineralg.ânewâ(42)
â min3 = Mineralg(String).ânewâ(42)
â
â â# => Error: no overload matches 'Mineralg(String).new' with type Int32â
When naming instance variables, prefix them with @. For class variables, use @@, like the @@planet our mineral species comes from. All objects built using this class will share this variable, and its value will be the same to all of them. (However, subclasses, which youâll see in the next section, all get their own copy with the value shared across the subclass.)
To name properties that can change, such as quantity in the code that follows, prefix them with property. For write-only properties that canât be read, use the prefix setter, like id in the following code. Trying to show them is an error:
classes_and_structs/classes.cr
â âclassâ Mineral
â @@planet = â"Earth"â
â
â getter name, hardness, crystal_struct
â setter id
â property quantity : Float32
â
â âdefâ âinitializeâ(@id : Int32, @name : String, @hardness : Float64,
â @crystal_struct : String)
â @quantity = 0f32
â âendâ
â
â âdefâ self.âplanetâ
â @@planet
â âendâ
â âendâ
â
â min1 = Mineral.ânewâ(101, â"gold"â, 1.0, â"cubic"â)
â min1.âquantityâ = 453.0f32 â# => 453.0â
â min1.âidâ â# => Error: undefined method 'id' for Mineralâ
â Mineral.âplanetâ â# => "Earth"â
â
â min2 = min1.âdupâ
â min1 == min2
Download
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
Management Strategies for the Cloud Revolution: How Cloud Computing Is Transforming Business and Why You Can't Afford to Be Left Behind by Charles Babcock(4118)
Ego Is the Enemy by Ryan Holiday(3958)
Offensive Shellcode from Scratch by Rishalin Pillay(3470)
Exploring Deepfakes by Bryan Lyon and Matt Tora(2925)
Liar's Poker by Michael Lewis(2793)
Learning C# by Developing Games with Unity 2021 by Harrison Ferrone(2776)
Speed Up Your Python with Rust by Maxwell Flitton(2773)
Linux Command Line and Shell Scripting Techniques by Vedran Dakic and Jasmin Redzepagic(2726)
Extreme DAX by Michiel Rozema & Henk Vlootman(2723)
OPNsense Beginner to Professional by Julio Cesar Bueno de Camargo(2717)
Agile Security Operations by Hinne Hettema(2714)
Robo-Advisor with Python by Aki Ranin(2693)
Essential Cryptography for JavaScript Developers by Alessandro Segala(2669)
Elevating React Web Development with Gatsby by Samuel Larsen-Disney(2664)
AI-Powered Commerce by Andy Pandharikar & Frederik Bussler(2572)
Cryptography Algorithms by Massimo Bertaccini(2564)
Distributed .NET with Microsoft Orleans by Bhupesh Guptha Muthiyalu Suneel Kumar Kunani(2561)
Python for ArcGIS Pro by Silas Toms Bill Parker(2556)
Incident Response Techniques for Ransomware Attacks by Oleg Skulkin(2551)