简体   繁体   中英

Creating CSV file in Ruby from Hash and txt file

I am a newbie to Ruby. I have a file that I want to open create a has and then read the file into a csv file. For further processing. For some reason I am not able to get all the entries in the hash into the file and in the correct format. column format.

This is the sample file

name: bc0090FB2.st.at.net
address: 192.168.1.2
state: 0
lastpingtime: 2013-02-13
name: bc0110FB2.st.at.net
address: 192.168.1.15
state: 1
lastpingtime: 2013-02-13
name: bc0150FB2.st.at.net
address: 192.168.1.12
state: 2
lastpingtime: 2013-02-13
name: bc0250FB2.st.at.net
address: 192.168.1.5
state: 3
name: bc0560FB2.st.at.net
address: 192.168.1.3
state: 1
lastpingtime: 2013-02-13
name: bc0058FB2.st.at.net
address: 192.168.1.4
state: 2
lastpingtime: 2013-02-13
name: bc0540FB2.st.at.net
address: 192.168.1.10
state: 3
lastpingtime: 2013-02-13
name: bc5890FB2.st.at.net
address: 192.168.1.6
state: 4
name: bc0520FB2.st.at.net
address: 192.168.1.8
state: 2
lastpingtime: 2013-02-13

This is the sample code

require 'csv'

splitup = {}

f = CSV.open("order3.txt", "r") do |fp|
  fp.each do |line|
    # Create a hash to capture each key value pair
    (key, value) =  line.chomp.split(":")
    splitup[key] = value

    namea = splitup["name"]
    addressa = splitup["address"]
    lastping = splitup["lastpingtime"]
    statea = splitup["state"]

    lineA = "#{namea} #{addressa} #{statea} #{lastping}"

    #verifies that the hash works

    puts lineA
  end
end

# trying to put the hash in a csv file 
CSV.open("order25.csv", "w") do |csv|
  csv << ['name', 'address', 'state', 'pingtime']

  splitup.each do |rows|
    csv << rows
  end
end

It's not quite clear what you want to achieve, however, the sample file you provided doesn't have a CSV like structure and, if you pasted it correctly, it seems to have a quite random pattern. In other words: name , address , state , lastpingtime keys don't appear in the same order in the origin text file.

To be able to transform the key/value groups structure (sample file) to a CSV structure you should have a standard pattern on the first one to be able to read it in groups of 4 rows and then merge them into a single CSV row.

In ruby to read a file n lines at a time you could something like this:

File.foreach("order3.txt").each_slice(4) do |lines|
  # 'lines' will be an array containing four lines
end

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