Home > Mobile >  Nested Ruby Hash to CSV
Nested Ruby Hash to CSV

Time:01-16

I have a nested hash as follow example:

{
    "0001" => {
        "All nodes" => [N001, N002, N003],
        "All links" => [N001.1, N002.1, N003.1],
        "Pumps" => [N001.2]
    },
    "0002" => {
        "All nodes" => [N004, N005, N006],
        "All links" => [N004.1, N005.1, N006.1],
        "Pumps" => [N005.2]
    },
    "0003" => {
        "All nodes" => [N007, N008, N009],
        "All links" => [N007.1, N008.1, N009.1],
        "Pumps" => [N007.2]
    }
}

Under Nodes are stored information like coordinates, under Links are stored inverts, diameters and storage and under Pumps are stored On/Off levels and discharge.

I would like to know if you have any idea for how to export to CSV the information that are stored in the hash but in the right column (which will be the hash keys (0001, 0002 and 0003)). As example, this is what I managed to make till now:

require 'CSV'
net=WSApplication.current_network
CSVsaveloc=WSApplication.file_dialog(false, "csv", "Comma Separated Variable File", "testexportcsv",false,true)
f = File.new(CSVsaveloc, "w")
CSV.open(CSVsaveloc,"wb") do |csv|
    csv << Hash.keys
    Hash.each do |key,values|
        csv << x.mean
        csv << y.mean
        csv << diameter.min
        csv << discharge.min
    end
end

Now I'm getting the export like this:

0001,0002,0003
246164.2646
518466.7589
300mm
0.01
246181.6492
518444.1727
250mm
0.005
246171.5763
518509.8948
500mm
0.1

(without spaces between lines, I had to add them because I couldn't paste in a proper way)
edit: changed it to "triple-backticks" formating.

BUT, I would like to have it like this:

0001,0002,0003
246164.2646,246181.6492,246171.5763
518466.7589,518444.1727,518509.8948
300mm,250mm,500mm
0.01,0.005,0.1

(again, without spaces between lines)

Thanks!

CodePudding user response:

From what I'm noticing, it seems that CSV inserts to a new line every time you run csv << . It might help to create an array for each line you're expecting, then append to CSV from there.

Expanding from the example code you gave earlier, maybe you can try this instead?

require 'CSV'
net=WSApplication.current_network
CSVsaveloc=WSApplication.file_dialog(false, "csv", "Comma Separated Variable File", "testexportcsv",false,true)
f = File.new(CSVsaveloc, "w")

# Create arrays
x_mean = []
y_mean = []
diameter_min = []
discharge_min = []

# Insert each value to corresponding array
Hash.each do |key, values|
    x_mean << x.mean
    y_mean << y.mean
    diameter_min << diameter.min
    discharge_min << discharge.min
end

# Insert each array to each line of CSV
CSV.open(CSVsaveloc,"wb") do |csv|
    csv << Hash.keys
    csv << x_mean
    csv << y_mean
    csv << diameter_min
    csv << discharge_min
end
  •  Tags:  
  • ruby
  • Related