String interpolation in Elixir
Bakery arithmetic dropped straight into strings with #{} and <>.
# Interpolation runs any expression inside a string; <> glues strings.
baker = "Marta"
loaves = 14
IO.puts("#{baker} baked #{loaves} loaves, #{div(loaves, 2)} of them rye")
label = "batch " <> "no. " <> "7"
IO.puts(label)
# to_string and inspect turn other values into printable text.
IO.puts("sold out? " <> to_string(loaves == 0))
IO.puts("the wholesale order: " <> inspect({:rye, 6}))
How it works
#{}runs any expression — a variable, then adiv— inside the string.<>concatenates plain literals into the batch label.to_stringandinspectturn a boolean and a tuple into printable text.
Keywords and builtins used here
IO
The run, in numbers
- Lines
- 11
- Characters to type
- 389
- Tokens
- 85
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 68 seconds.
Step 1 of 3 in Strings & sigils, step 16 of 27 in Language basics.