O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Other Ways to Run Code Fragments

We can use the function Code.eval_quoted to evaluate code fragments, such as those returned by quote.

 
iex>​ fragment = ​quote​ ​do​: IO.puts(​"hello"​)
 
{{:.,[],[{:__aliases__,[alias: ​false​],[:IO]},:puts]},[],[​"hello"​]}​​
 
iex>​ Code.eval_quoted fragment
 
hello
 
{:ok,[]}

By default, the quoted fragment is hygienic, and so does not have access to variables outside its scope. Using var!(:name), we can disable this feature and allow a quoted block to access variables in the containing scope. In this case, we pass the binding to eval_quoted as a keyword list.

 
iex>​ fragment = ​quote​ ​do​: IO.puts(var!(a))
 
{{:., [], [{:__aliases__, [alias: ​false​], [:IO]}, :puts]}, [],
 
[{:var!, [context: Elixir, ​

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required