[Ruby] CSV to Hash
這一小段程式是將 CSV 塞成 Hash 的暴力方式 ..。初衷是希望讀入 CSV 的第一行為各 Hash 的 KEY,其餘行為 VALUE。
也就是
name,number,country
alice,1,TAIWAN
bob,2,USA
cindy,3,JAPAN
能被包成 [ { :name => “alice”, :number => “1″, :country => “TAIWAN” } ,{ :name => “bob”, :number => “2″, :country => “USA” },{ :name => “cindy”, :number => “3″, :country => “JAPAN” } ]
require "csv"
class << Hash
def create(keys, values)
self[*keys.zip(values).flatten]
end
end
sp_array = Array.new
first = true
first_row = []
CSV.open("XXX.csv","r"){|row|
if first
first = false
first_row = row.to_a
else
result = Hash.create(first_row,row.to_a)
sp_array << result
end
}
About this entry
You’re currently reading “[Ruby] CSV to Hash,” an entry on Handlino
- Author:
- xdite
- Published:
- July 25th, 2008 / 4pm
- Category:
- Ruby
No comments
Jump to comment form | comments rss [?] | trackback uri [?]