Importing CSV data into a ruby array/variable

梦想与她 提交于 2019-12-03 21:02:33

If you try to use FasterCSV in Ruby 1.9 you get a warning saying that the standard Ruby 1.9 CSV library is actually faster. So I used the standard Ruby CSV library. This should work in Ruby 1.9 or 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")

The output of this code is:

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

Now what I want you to do is read every line of this code carefully and try to understand what it does and why it is necessary. This will make you a better programmer in the long run.

You could improve this code to lazily load the CSV file the first time it is required.

I'll demonstrate the dirt-simple method. Stuffing everything in a hash as David Grayson did is far more efficient in the long run, but for a run-a-few-times script this might be sufficient.

require 'csv'
config = CSV.read('config.csv')
config.shift # Get rid of the header
# We're done! Start using like so:
p config.assoc("Computer").last #=>" 02-46-81-02-46-cd" 

If the leading space is unwanted:

config = CSV.read('config.csv', {:col_sep => ', '})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!