Skip to content

Instantly share code, notes, and snippets.

@fogus
Forked from blacktaxi/ruby-fmt.clj
Created January 25, 2012 20:38
Show Gist options
  • Select an option

  • Save fogus/1678577 to your computer and use it in GitHub Desktop.

Select an option

Save fogus/1678577 to your computer and use it in GitHub Desktop.

Revisions

  1. @blacktaxi blacktaxi revised this gist Jan 25, 2012. 1 changed file with 7 additions and 0 deletions.
    7 changes: 7 additions & 0 deletions ruby-fmt.clj
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,10 @@
    ; 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]))

  2. @blacktaxi blacktaxi created this gist Jan 25, 2012.
    17 changes: 17 additions & 0 deletions ruby-fmt.clj
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    (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)}!"))