Created
January 25, 2012 14:42
-
-
Save blacktaxi/1676575 to your computer and use it in GitHub Desktop.
Ruby-like string interpolation in Clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; 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)}!")) |
At least you have an understanding on how it's done!
Where is that macro in the realms of the new contrib which is now modular?
It's in clojure.core.strint : https://github.com/clojure/core.incubator/blob/master/src/main/clojure/clojure/core/strint.clj , it's updated even.
No, my mistake, it's the same macro from old contrib.
that's why I love this language :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sure, it's in old contrib, but our stuff is way better!