Rails summing the values in a hash thats sorted using Regex

I have a query here that involves a few elements, as a result my brain is climbing out my ears. i have a hash that's populated with symbols as keys and numbers as values, the hash is used as both a storage for methods(via method_missing) and the results from a SQL Query. an example of what it looks like:

@data = {:number_of_african_male_senior_managers => 0, :number_of_african_male_middle_managers => 2, :number_of_african_male_junior_managers => 3, :number_of_white_female_senior_managers => 5... ect}

the sql query runs and gathers a count of how many male african senior managers there are and saves that. now i am trying to create a total column that will show me how many senior managers there are in total, regardless of gender or race. I was thinking something like this:

 def extract_position_totals(position)
   totals = @data.select {|k,v| k.to_s.match(/#{position}/)}

 end 

<-note this is where i am stuck this method is not finished

now my problem comes the above code will go through the key/value pairs and pick out which ones are specified in the parameters, i was going to inject, but how can i sum the values of those keys when the keys will have different names??

so at the end of the day I would like to call something like this: @ee_demographics_presenter.extract_position_totals(senior) and have it return =>5

any help is much appreciated. :D

Answers


One liner with inject:

def extract_position_totals(position)
   @data.inject(0) { |memo, ary| ary[0] =~ /#{position}/ ? memo + ary[1] : memo }
end

Use to get sum values of those keys if keys has different name :

not_match_count = 0
@data.map{|k, v| not_match_count+=v if !k.to_s.match(/#{position}/)}

Need Your Help

Securing HTTPS internet portal without access to user IP address?

security http https load-balancing

I am trying to rework a small online portal that has a few inherit security flaws. Most notably due to the network architecture and load balancers the application isn’t able to access the requestin...

Including Javascript and css in Master pages and User Controls in asp.net

asp.net javascript master-pages user-controls

I am trying to include the js and css in my code behind in my master pages and user controls in Page_Load event.