Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)}!"))
@susl

This comment has been minimized.

Copy link

commented Jan 25, 2012

Батька :)

@alandipert

This comment has been minimized.

Copy link

commented Jan 26, 2012

Ahoy, fellow interpolist. We use many of the same tricks :-)

@blacktaxi

This comment has been minimized.

Copy link
Owner Author

commented Jan 26, 2012

Was exactly my thought! :D
BTW, I didn't know there's already a macro for interpolation in the contrib? It's called <<. Source: https://github.com/clojure/clojure-contrib/blob/62078f31f425a0bf4be6508a51ac1fa8ce09ea51/src/main/clojure/clojure/contrib/strint.clj#L49
After been pointed out to that code I felt like I've just reinvented the bicycle about my creation.

@alandipert

This comment has been minimized.

Copy link

commented Jan 26, 2012

Sure, it's in old contrib, but our stuff is way better!

@djhworld

This comment has been minimized.

Copy link

commented Jan 26, 2012

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?

@blacktaxi

This comment has been minimized.

Copy link
Owner Author

commented Jan 26, 2012

@blacktaxi

This comment has been minimized.

Copy link
Owner Author

commented Jan 26, 2012

No, my mistake, it's the same macro from old contrib.

@ertugrulcetin

This comment has been minimized.

Copy link

commented Jun 22, 2017

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
You can’t perform that action at this time.