56 Wha...">

How to execute code from a string variable in Crystal?

I like it evalin Ruby because it works quite simply:

eval("puts 7 * 8") # => 56

What is the equivalent evalin Crystal? I know that we can do something similar with a macro:

macro eval(code)
 {{code.id}}
end

eval("puts 7 * 8") # => 56

But this will not work with runtime values:

a = "yo"
eval("puts #{a}") # => prints nothing
+4
source share
1 answer

Crystal is a compiled language, while Ruby is interpreted. This greatly complicates the evaluation of code at runtime.

In your example, the macro expands at compile time, so your program is actually simple puts 7 * 8. In other words, it works because the code is known at compile time.

, , Crystal . , Crystal. "eval", , Crystal, .

, . , , , .

, eval Ruby , , .

+12

All Articles