Skip to content

Instantly share code, notes, and snippets.

@leobm
Forked from fogus/ruby-fmt.clj
Created December 19, 2022 01:44
Show Gist options
  • Save leobm/7aefef03d50b3bad054bb43af4fcded7 to your computer and use it in GitHub Desktop.
Save leobm/7aefef03d50b3bad054bb43af4fcded7 to your computer and use it in GitHub Desktop.
Ruby-like string interpolation in Clojure
; Ruby has an awesome feature -- string interpolation. Read about it on the internet.
; On the other hand, Clojure only has cumbersome Java string formatting, which can not be
; used without pain after you've tried Ruby.
; So here's this simple macro that basically allows you to do most things you could do
; with Ruby string interpolation in Clojure.
(ns eis.stuff
(:require [clojure.string]))
(defmacro fmt [^String string]
(let [-re #"#\{(.*?)\}"
fstr (clojure.string/replace string -re "%s")
fargs (map #(read-string (second %)) (re-seq -re string))]
`(format ~fstr ~@fargs)))
;; test the macro
(def name "Mister")
(def surname "Metaphor")
(def seq [1 2 3])
(println (fmt "Hello #{name} #{(clojure.string/join \" \" surname)}!"))
(println (fmt "Frist element of #{seq} is #{(first seq)}!"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment