Jessie Richardson
Jessie Richardson

Reputation: 958

Extracting Value of Key in Atom by Converting String to Symbol

I have an atom:

{:answer1 "yes", :answer2 "no", :answer3 "maybe"}

And I want to be able to use the variable x to extract the value of :answerx.

In my REPL, when I test out how to append to a string and then convert to symbol, this works:

(symbol (str ":answer" 2))

Result is :answer2. However, when I attempt to do this within the atom, I get a result of nil:

(get @answers-atom (symbol (str ":answer" 2)))

Any idea why this might be happening?

Upvotes: 0

Views: 617

Answers (1)

Sam Estep
Sam Estep

Reputation: 13304

It seems that you're mixing up symbols and keywords. For instance, in the map that you give at the beginning of your question, :answer1, :answer2, and :answer3 are keywords, but (symbol (str ":answer" 2)) is a symbol. To get a keyword, you need to instead use the keyword function:

(def m {:answer1 "yes" :answer2 "no" :answer3 "maybe"})

(get m (symbol (str ":answer" 2))) ;=> nil

(get m (keyword (str "answer" 2))) ;=> "no"

Upvotes: 9

Related Questions