I have one hash
h1 = {"Cust1"=>500, "Cust4"=>400, "Cust2"=>100, "Cust3"=>100}
I want to insert this hash into a CSV file with the ranking of keys according to their value.
The sample output should look like this
ID,Sales,Rank Cust1,500,1 Cust4,400,2 Cust2,100,3 Cust3,100,3
I have to write the program in Ruby.
You can use each_with_index
method of hash
arr = [['ID', 'Sales', 'Rank']]
h1.each_with_index do |(key, value), index|
arr << [key, value, index + 1]
end
arr #[["ID", "Sales", "Rank"], ["Cust1", 500, 1], ["Cust4", 400, 2], ["Cust2", 100, 3], ["Cust3", 100, 4]]
Code for CSV
h1 = {"Cust1"=>500, "Cust4"=>400, "Cust2"=>100, "Cust3"=>100}
# You can skip following `sort_by` line if your hash is already ordered by desc value
h1 = h1.sort_by {|_k,v| v}.reverse.to_h
h2 = h1.group_by {|k,v| v }
require 'csv'
CSV.open("myfile.csv", "w") do |csv|
csv << ['ID', 'Sales', 'Rank']
h2.each_with_index do |(key, values), index|
values.each do |value|
csv << [value[0], key, index + 1]
end
end
end