Search code examples
crystal-lang

How-to do regex in macros?


{% nilable = /\:\:Nil|\?$/.match(type) %}

It doesn't seem to work: undefined macro method 'RegexLiteral#match'.


Solution

  • Macros::StringLiteral has =~ instance:

    {% type = "Module::Nil" %}
    {% p type =~ /\:\:Nil|\?$/ %} #=> true
    
    {% type = "Module::Null" %}
    {% p type =~ /\:\:Nil|\?$/ %} #=> false