如果您嘗試在Ruby 1.9中使用FasterCSV,您會收到警告,說標準的Ruby 1.9 CSV庫實際上更快。所以我使用了標準的Ruby CSV庫。這應該在Ruby 1.9或1.8.7中工作。
require 'csv'
module MyConfig
@mac_address_hash = {}
CSV.foreach("config.csv") do |row|
name, mac_address = row
next if name == "Name"
@mac_address_hash[name] = mac_address
end
puts "Now we have this hash: " + @mac_address_hash.inspect
def self.mac_address(computer_name)
@mac_address_hash[computer_name]
end
end
puts "MAC address of Desktop: " + MyConfig.mac_address("Desktop")
這段代碼的輸出是:
Now we have this hash: {"Computer"=>" 02-46-81-02-46-cd", "Desktop"=>" 01-23-45-67-89-ab"}
MAC address of Desktop: 01-23-45-67-89-ab
現在我要你做的就是仔細閱讀這段代碼的每一行,並嘗試瞭解它做什麼,以及爲什麼它是必要的。從長遠來看,這會讓你成爲更好的程序員。
您可以改進此代碼以在第一次需要時延遲加載CSV文件。
感謝一大堆!我幾乎在那裏。你是最棒的 – IMcD23