2

I have built a form tag and gotten values selected from a user. This is what I get:

params[:user_answer_ids] = {"170"=>["599"], "162"=>["561", "563", "565"], "160"=>["549", "550"]}

Now I want to convert all string in this hash to int, like:

params[:user_answer_ids] = {170=>[599], 162=>[561, 563, 565], 160=>[549, 550]}

I want to convert to int because I want to compare question and answer ids later. Currently I have to use to_i method when looping in a hash, so I want to know whether there is any way to convert all string to int at once.

1 Answer 1

3

You could fake it...

h={"170"=>["599"], "162"=>["561", "563", "565"], "160"=>["549", "550"]}
h.default_proc = proc{|h,k| h.key?(k.to_s) ? h[k.to_s].map(&:to_i) : nil}
p h[162]

Leaves the data unchanged.

Sign up to request clarification or add additional context in comments.

2 Comments

Shouldn't be best to just retrieve the key and if it's not nil convert it to_i?
I like it, with the data unchanged.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.