Using csv data to create a hash of each occurance of a value in Ruby

I am trying to take data from a csv and create a count from the medicine column.
Sample data of csv looks like:
name medicine age address
molly tylenol 21 1203
tyler advil 19 1008
bob tylenol 41 192
sara alieve 22 202

How would I take in each row and start a key value pair of medicine , if it does not already exist, with the medicine as the key and the value as the count. So if the same medicine is used in the next row, it will just increase the count and not create a duplicate key.

CSV.foreach(my_file, headers: true) do |row|
    # psuedocode
    # if row's medicine value does not exist, create a hash with the count  e.g. 
       tylenol: 1
    # if row's medicine value does exist (has_key?), update the count in the 
       matching existing key e.g. tylenol: 2

  end

When you create your Hash, you can tell it to have a default value of zero in case referenced at a key that isn’t already in there. So then when you hit a row from your table, you can just add one to the hash element keyed by the medicine.

Example from IRB:

irb(main):002:0> it = Hash.new(0)
=> {}
irb(main):003:0> it["izzatso"] += 1
=> 1
irb(main):004:0> it
=> {"izzatso"=>1}
2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.