From: Rob Biedenharn Date: 2009-05-03T05:42:10+09:00 Subject: Re: n00b ? re: CGI Hash and arrays On May 2, 2009, at 4:27 PM, Jeff Leggett wrote: > Hi, n00b here, and got myself stumped on something I thought was easy. > > I get CGI params returned as: > > params: {"conf_mod"=>["20"], "conf_impact"=>["10"], > "avail_impact"=>["5"], "integrity_impact"=>["5"], > "authorization"=>["5"], "integrity_mod"=>["5"]} > > I just want to add up the values in the hash keys. Seems simple, > but an > hour or so later, after trying numerous things no go. Any help > appreciated. So you want to end up with total == 50, right? The values are arrays of strings, so you need to sum up the (single) values after turning them to integers. total = 0 values.each_value {|v| v.each {|s| total += s.to_i } } puts "total: #{total}" irb> total = 0 => 0 irb> values.each_value {|v| v.each {|s| total += s.to_i } } => {"conf_mod"=>["20"], "conf_impact"=>["10"], "avail_impact"=>["5"], "integrity_impact"=>["5"], "authorization"=>["5"], "integrity_mod"=>["5"]} irb> puts "total: #{total}" total: 50 => nil -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com > #!/usr/bin/ruby > > require "cgi" > > cgi = CGI.new('html4') > values = cgi.params > #values.each_value { |y| total += (eval y.join('+')) } > #values.each_value { |x| total += x[0] } > #values.each_value do |v| puts v end > #cgi.header > cgi.out() do > cgi.html() do > cgi.head{ cgi.title{"TITLE"} } + > cgi.body() do > cgi.pre() do > CGI::escapeHTML( > "params: " + cgi.params.inspect + "\n" > "total: " + puts(total) + "\n" > ) > end > end > end > end > -- > Posted via http://www.ruby-forum.com/. >