Crystal For Rubyists
  • Know Ruby? Enter Crystal!
  • book
    • Chapter 1: Why Crystal?
    • Chapter 2: Installing Crystal
    • Chapter 3: Writing Your First Crystal Program
    • Chapter 4: Creating a new project
    • Chapter 5: Testing
    • Chapter 6: FizzBuzz
    • Chapter 7: Types and Method Overloading
    • Chapter 8: Concurrency and Channels
    • Chapter 9: Macros and Metaprogramming
    • Chapter 10: C Bindings
Powered by GitBook
On this page
  1. book

Chapter 9: Macros and Metaprogramming

We love Ruby because of its’ dynamic nature and metaprogramming! Unlike Ruby, Crystal is a compiled language. That’s why there are some key differences.

  • There’s no eval.

  • There’s no send.

In Crystal we use Macros to achieve this kind of behaviour and metaprogramming. You can think of Macros as ‘Code that writes/modifies code’.

P.S: Macros are expanded into code at compile-time.

Check this.

macro define_method(name, content)
  def {{name}}
    {{content}}
  end
end

define_method foo, 1
# This generates:
#
#     def foo
#       1
#     end

foo # => 1

In the example we created a macro named define_method and we just called that macro like a normal method. That macro expanded into

  def foo
    1
  end

Pretty cool! We got eval behaviour at compile-time.

Macros are really powerful but there’s one rule that you can’t break.

A macro should expand into a valid Crystal program

PreviousChapter 8: Concurrency and ChannelsNextChapter 10: C Bindings

Last updated 6 years ago