HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Split post string into hash

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
intohashpostsplitstring

Problem

if(env['REQUEST_METHOD'] == 'POST')
  $post = {}
  post = env['rack.input'].read.split('&')
  post_split = Array.new
  post.each{|x| post_split << x.split('=')}
  post_split.each{|x|
    $post[x[0]] = x[1]
  }
end


What would be a nice way to do this? I have a string like:

"a=b&c=d"


and i'm trying to get it into a hash like

{:a=>'b',:c=>'d'}


This code works but it is just terrible, and I can't access the keys with

$post[:a]


only

$post['a']

Solution

better way of such parsing is not to reinvent the wheel and use existing ruby functionality

require "cgi"
post = CGI.parse "a=b&c=d"
# => {"a"=>["b"], "c"=>["d"]}


hash values are arrays here, but it makes sense, as you can have several vars in your query string with the same name

for the second part of your question (accessing the keys as symbols) you can use .with_indifferent_access method provided by ActiveSupport (it is already loaded if you use rails)

post.with_indifferent_access[:a]
# => ["b"]

Code Snippets

require "cgi"
post = CGI.parse "a=b&c=d"
# => {"a"=>["b"], "c"=>["d"]}
post.with_indifferent_access[:a]
# => ["b"]

Context

StackExchange Code Review Q#4282, answer score: 5

Revisions (0)

No revisions yet.