I am using the ruby mysql2 gem to work with a database. I want to list all the countries per region in one table, then add up the hits per region.
Normally I would use the mysql SUM function, but the gem returns the headers so this is not possible.
Instead, I am getting the hit count for each country per region and add it up.
The gem returns 1 array per result and I need to get that result and add it to a running total per region.
This is my code:
#!/usr/bin/ruby -w
# simple.rb - simple MySQL script using Ruby MySQL module
require "rubygems"
require "mysql2"
client = Mysql2::Client.new(:host => "localhost", :username => "root", :database => "cbscdn")
regions = client.query("select Id from Regions")
regions.each(:as => :array) do |rid|
hit = client.query("select hits from Countries where Regions_Id='#{rid}'")
hit.each(:as => :array) do |a|
a.map do |x|
x.to_i
end
end
end
How can I implement the running count per region?
If for any reason you don’t want to delegate it to the database engine, you can do this way:
(for simplicity, I assume your results are already arrays)