Ruby/ RoR - String Hash to Integer Hash
I have an Hash @answers = params[:Answers].to_hash;
<%= debug开发者_开发技巧 @answers %>
outs
---
"1": "2"
"7": "3"
"6": "4"
"4": "0"
Need to make the @answers to one like below
@ans = {1 => 2, 7 => 3, 6 => 4, 4 => 0}
<%= debug @answers %>
outs
---
1: 2
7: 3
6: 4
4: 0
Black magic wizard reporting in:
answers = {"1" => "2", "3" => "4"}
Hash[*answers.to_a.flatten.map(&:to_i)] # => {1=>2, 3=>4}
Here is the code
@ans = {"1" => "2", "7" => "3", "6" => "4", "4" => "0"}
@foo_hash ={} #new_hash
@ans.each_pair{|k,v| @foo_hash.store(k.to_i,v.to_i)}
The @foo_hash will be {1 => 2, 7 => 3, 6 => 4, 4 => 0}
Then you can <%= debug @foo_hash %> to get the output in your YAML format
精彩评论