1

If I have a map like this:

(def foo {:bar "foobar"})

And I've been passed the key :bar as a string (i.e. ":bar") I want to be able to access the value from the map doing something like

(get foo (symbol ":bar"))

which I thought would work, because (symbol ":bar") is :bar ... but it just returns nil

stukennedy
  • 1,088
  • 1
  • 9
  • 25

3 Answers3

3

If you need to make from string ":asd" a keyword :asd you do something like this:

> (= (read-string ":asd") (keyword (subs ":asd" 1)) :asd)
true

Your code with (symbol ":asd") just print itself like :asd but is actually a symbol, not keyword.

JustAnotherCurious
  • 2,208
  • 15
  • 32
  • thanks for that ... it feels a bit hacky to wrangle the string first, but looks like that's the only way. – stukennedy Oct 12 '15 at 15:47
  • 1
    It is a bit hacky, because you have the string `":asd"` to begin with. Where did that string come from? More likely, you can address this problem closer to its source, by generating a more reasonable string input in the first place. – amalloy Oct 13 '15 at 01:09
  • yeah I ended up doing just that ... I used `(name ":asd")` before it got stored ... so I could just used `(keyword "asd")` on the string. Thanks for the advice. – stukennedy Oct 23 '15 at 15:44
0

If your string really is ":bar", just do a replace to remove the colon and then use keyword to convert it to a keyword.

(def foo {:bar "foobar"})

(foo (keyword (clojure.string/replace ":bar" #"\:" ""))) => "foobar"

north_celt
  • 25
  • 6
0

This works:

((read-string ":bar") {:bar "foobar"})
=> "foobar"

Or of course:

(get {:bar "foobar"} (read-string ":bar"))
shmish111
  • 3,697
  • 5
  • 30
  • 52