From 18a8fd8ac5dfd06254082993974a937d15f2dc05 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sun, 18 Mar 2018 13:33:21 -0500 Subject: [PATCH] Add String Interpolation With Quoted Strings as a reasonml til --- README.md | 3 +- ...tring-interpolation-with-quoted-strings.md | 35 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 reason/string-interpolation-with-quoted-strings.md diff --git a/README.md b/README.md index fae847f..5cd4f8b 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_643 TILs and counting..._ +_644 TILs and counting..._ --- @@ -471,6 +471,7 @@ _643 TILs and counting..._ - [Pattern Match On Exceptions](reason/pattern-match-on-exceptions.md) - [Quickly Bootstrap A React App Using Reason](reason/quickly-bootstrap-a-react-app-using-reason.md) - [String Interpolation With Integers And Sprintf](reason/string-interpolation-with-integers-and-sprintf.md) +- [String Interpolation With Quoted Strings](reason/string-interpolation-with-quoted-strings.md) ### Ruby diff --git a/reason/string-interpolation-with-quoted-strings.md b/reason/string-interpolation-with-quoted-strings.md new file mode 100644 index 0000000..24ef0e2 --- /dev/null +++ b/reason/string-interpolation-with-quoted-strings.md @@ -0,0 +1,35 @@ +# String Interpolation With Quoted Strings + +Stapling strings together with the `++` operator can be tedious and clunky. +If you have string variables that you'd like to interpolate, you can piece +them together much more easily using [quoted +strings](https://reasonml.github.io/docs/en/string-and-char.html#quoted-string). + +We can get close to a solution with the standard quoted string syntax. + +```reason +let greeting = (greetee) => { + {|Hello, $(greetee)!|} +}; + +Js.log(greeting("World")); // => "Hello, $(greetee)!" +``` + +This isn't quite right though. We have to take advantage of a preprocessing +hook provided by +[Bucklescript](https://bucklescript.github.io/docs/en/common-data-types.html#interpolation). +The `j` hook supports unicode and allows variable interpolation. + +```reason +let greeting = (greetee) => { + {j|Hello, $(greetee)!|j} +}; + +Js.log(greeting("World")); // => "Hello, World!" +``` + +To use this pre-processor we have to include `j` in the quoted string like +so `{j|...|j}`. + +See a [live example +here](https://reasonml.github.io/en/try.html?reason=DYUwLgBA5gTi4EsB2UIF4IApbzPAlOgHwQDeAUBGQFYA+AEiMMAPYA0EAJNnOAQIS1qAX3LCA3OXIApAM4A6VlB65kygEQB1FjGAATdfnzigA).