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.
#!/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
params.each do |key, val|
num_str = val[0]
num = num_str.to_i
total += num
end
Once you understand that, you can make it briefer:
params.each do |key, val|
total += val[0].to_i
end
…however if it’s possible that the arrays can contain more than one
string, then you need to loop over each array too. As per Rob
Biedenharn’s solution: