简体   繁体   中英

How to sort_by dates in csv using ruby

This my csv output ,I need to sort the rows according to the earliest date of States node.

require 'nokogiri'
require 'csv'
xmlfile = File.read("test3.xml")
doc = Nokogiri::XML(xmlfile)
all = []
doc.css('Firm').each_with_index do |firm,i|
 firstchild  = []
 secondchild =[]
firm.css('States').each do |rgltr_addr_node|
 if rgltr_addr_node.has_attribute?("RgltrCd")
  RgltrCd =rgltr_addr_node.attributes["RgltrCd"]&&rgltr_addr_node.attributes["RgltrCd"].value
 else 
 RgltrCd = "NA"
end
if rgltr_addr_node.has_attribute?("St")
  St = rgltr_addr_node.attributes["St"] && rgltr_addr_node.attributes["St"].value
else
St = "NA"
end
if rgltr_addr_node.has_attribute?("Dt")
  Dt = rgltr_addr_node.attributes["Dt"] && rgltr_addr_node.attributes["Dt"].value
else 
Dt ="NA"
end
firstchild[0] = RgltrCd 
firstchild[1] = St
firstchild[2] = Dt
end
firm.css('Filing').each do |filing_node|
if filing_node.has_attribute?("Dt")
  Dt = filing_node.attributes["Dt"] && filing_node.attributes["Dt"].value
else
Dt ="NA"
end
if filing_node.has_attribute?("FormVrsn")
  FormVrsn = filing_node.attributes["FormVrsn"] && filing_node.attributes["FormVrsn"].value
else 
FormVrsn ="NA"
end
  secondchild[0] = Dt 
  secondchild[1] = FormVrsn
 end
end
all << firstchild + secondchild 
end

I used the following looping for data to display in each row of csv:

CSV.open('new_test3_file.csv', 'wb' ) do |row|
    row << ['States', 'Filing']
    all.each do |data|
        row << data
    end

Can any one help me in sorting this by date?

Try this:

csv_rows = []
CSV.foreach('new_test3_file.csv', headers: true) do |row|
  csv_rows << row.to_h
end

csv_rows.sort_by{ |row| row['Dt'] }

Here, CSV is completely text data of string provided by comma.

all is array of data to be written on CSV file so I suggest you to sort data inside all as per your need first and then write on csv file.

all = [["Ut", "2009-01-12"], ["TY", "2003-12-21"], ["Rt", "2008-05-20"]] 

Now sort it like below if your date of state is 2nd value at inner array

> all.sort! { |a,b| DateTime.parse(a[1]) <=>  DateTime.parse(b[1]) }
 # => [["TY", "2003-12-21"], ["Rt", "2008-05-20"], ["Ut", "2009-01-12"]]

Now you can write this sorted data on csv file.

Or you can use, (As @Stefan suggested in below comment)

all.sort_by! { |a| a[1] }  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM