0

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

legendary_rob
  • 12,792
  • 11
  • 56
  • 102

2 Answers2

1

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}/)}
swati
  • 1,719
  • 10
  • 13
1

One liner with inject:

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