I assume the key-value pairs of h1
are not necessarily in order of decreasing values.
We need to make two calculations to construct the CSV file.
order = h1.sort_by { |_,v| -v }
#=> [["Cust1", 500], ["Cust4", 400], ["Cust2", 100], ["Cust3", 100]]
nbr_ranks = order.map(&:last).uniq.size
#=> 3
The file can be constructed as follows.
require 'csv'
CSV.open('t.csv', 'w') do |csv|
csv << ['ID', 'Sales', 'Rank']
last_val = order.first.last
order.each do |name, val|
unless val == last_val
nbr_ranks -= 1
last_val = val
end
csv << [name, val, nbr_ranks]
end
end
puts File.read('t.csv')
ID,Sales,Rank
Cust1,500,1
Cust4,400,2
Cust2,100,3
Cust3,100,4
If the key-value pairs of h1
are guaranteed to be in order of decreasing values (as in the example), there is no need to compute the array order
.
nbr_ranks = order.map(&:last).uniq.size
#=> 3
CSV.open('t.csv', 'w') do |csv|
csv << ['ID', 'Sales', 'Rank']
last_val = h1[h1.keys.first]
h1.each do |name, val|
unless val == last_val
nbr_ranks -= 1
last_val = val
end
csv << [name, val, nbr_ranks]
end
end
Note:
last_val = h1[h1.keys.first]
#=> 500