Say I have
str = "a=2&b=3.05&c=testing"
I run
require 'cgi'
out = {}
CGI::parse(str).each { |k,v| out[k] = v[0] }
When I output a, 2 is a string, when I want it to be an Int
out['a'] // "2" (instead of int 2)
out['b'] // "3.05" (instead of float 3.05)
Is there any way to correct the types from the query string?
Update:
Added this method to test for numbers
def is_a_number?(s)
s.to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/) == nil ? false : true
end
and during the parse
CGI::parse(url).each do |k,v|
val = v[0]
if is_a_number? val
val = val.include?('.') ? val.to_f : val.to_i
end
out[k] = val
end
Seems to work with basic examples. Is there anything unsafe about this?
Edited: This works