How to execute code from a string variable in Crystal?
I like it eval
in Ruby because it works quite simply:
eval("puts 7 * 8") # => 56
What is the equivalent eval
in 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
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 , , .