Book Image

Crystal Programming

By : George Dietrich, Guilherme Bernal
Book Image

Crystal Programming

By: George Dietrich, Guilherme Bernal

Overview of this book

Crystal is a programming language with a concise and user-friendly syntax, along with a seamless system and a performant core, reaching C-like speed. This book will help you gain a deep understanding of the fundamental concepts of Crystal and show you how to apply them to create various types of applications. This book comes packed with step-by-step explanations of essential concepts and practical examples. You'll learn how to use Crystal’s features to create complex and organized projects relying on OOP and its most common design patterns. As you progress, you'll gain a solid understanding of both the basic and advanced features of Crystal. This will enable you to build any application, including command-line interface (CLI) programs and web applications using IOs, concurrency and C bindings, HTTP servers, and the JSON API. By the end of this programming book, you’ll be equipped with the skills you need to use Crystal programming for building and understanding any application you come across.
Table of Contents (26 chapters)
1
Part 1: Getting Started
5
Part 2: Learning by Doing – CLI
10
Part 3: Learn by Doing – Web Application
13
Part 4: Metaprogramming
18
Part 5: Supporting Tools

Iterating type variables

One of the most common use cases for type introspection is that of iterating over a type's instance variables. The simplest example of this would be adding a #to_h method to an object that returns Hash using the type's instance variables for the key/values. This would look like this:

class Foo
  getter id : Int32 = 1
  getter name : String = "Jim"
  getter? active : Bool = true
 
  def to_h
    {
      "id"     => @id,
      "name"   => @name,
      "active" => @active,
    }
  end
end
 
pp Foo.new.to_h

Which, when executed, would print the following:

{"id" => 1, "name" => "Jim", "active" => true}

However, this is less than ideal because...