with-out-str

added
1.0

ns
clojure.core

type
macro

(with-out-str & body)

Evaluates exprs in a context in which *out* is bound to a fresh
StringWriter.  Returns the string created by any nested printing
calls.

                ;; Instead of printing, the following will place the output normally
;; sent to stdout into a string.

user=> (with-out-str (println "this should return as a string"))
"this should return as a string\
"

            
                ;; `time` prints the elapsed time. `with-out-str` can put it into a variable.

(def elapsed
  (with-out-str
    (time (last (range 10000)))))

elapsed
;=> "\\"Elapsed time: 49.363055 msecs\\"\
"

            
                (defmacro with-out-str-data-map
  [& body]
  `(let [s# (new java.io.StringWriter)]
     (binding [*out* s#]
       (let [r# ~@body]
         {:result r#
          :str    (str s#)}))))

(with-out-str-data-map (do
                         (println "Clojure is the best!")
                         2))

;;=> {:str "Clojure is the best!\
", :result 2}
            
                (defn pp-str [x]
  (with-out-str (clojure.pprint/pprint x))


(pp-str {:foo "foo" :bar "bar"})
;;=> "{:foo \\"foo\\", :bar \\"bar\\"}\
"