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.
1
macro define_method(name, content)
2
def {{name}}
3
{{content}}
4
end
5
end
6
7
define_method foo, 1
8
# This generates:
9
#
10
# def foo
11
# 1
12
# end
13
14
foo # => 1
Copied!
In the example we created a macro named define_method and we just called that macro like a normal method. That macro expanded into
1
def foo
2
1
3
end
Copied!
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
Copy link