Making Elixir write a program for itself

I am fairly new to programming and Elixir in general but I have a task in elixir and it goes as follows:
“Can you make Elixir write a program for itself? Put this code into a file called script.ex with
File.write/2 : IO.puts "This file was generated from Elixir" and then make it run by running
elixir that-file.ex .”

I have tried numerous ways to tackle this but to no avail, could anyone help me by showing me the proper way to implement this with an explanation?

The best I could manage was to create the required file with the text IO.puts This file was generated from Elixir without any “”

I’m not sure I fully understand the requirements, but this is what I came up with.

The script below has two parts, a module definition with the desired functionality and then the actual function calls at the bottom. Run elixir that-file.exs in your terminal you should see “This file was generated from Elixir”

# that-file.exs

defmodule MyScriptWriter do
  # define module attribute @script_location which we can use as a constant
  @script_location "./script.exs"

  def write_script do
    # write the script to @script_location
    # Note: you must "escape" the interior quotation marks with a forward-slash
    File.write!(@script_location, "IO.puts \"This file was generated from Elixir\"")

  def run_script do
    # read the the string generated by write_script and evaluate it
    script =!(@script_location)

# these commands get executed when that-file.exs is run

Hey bluejay!
While I am not accustomed to everything you mentioned here I believe the part I had missed was the interior quotation marks escaping which seems to have solved it :slight_smile:
I have tried my simple version and yours and both are working as intended, thank you for the help

1 Like

You did correctly, the only miss was the lack of the quotes, that would prevent elixir from executing the file because of the incorrect syntax. To interpolate quotes inside a string you can escape them using \ like bluejay did, also have a look at other ways to do it, which would be nicer for long texts.