繁体   English   中英

将CSV数据导入ruby数组/变量

[英]Importing CSV data into a ruby array/variable

我正在尝试使用CSV作为SiriProxy项目插件中的设置文件来使用wake-on-lan。 这个项目基于ruby。

所以csv如下:

Name, MACAddress
Desktop, 01-23-45-67-89-ab
Computer, 02-46-81-02-46-cd

等等...

所以我想要发生的是,例如当变量userAction是“桌面”时,我查询CSV并将MAC地址返回到另一个变量。 我迷失了如何做到这一点。 我见过csv和faster_csv,但不知道如何让这些工作像这样。

提前致谢!

如果您尝试在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文件。

我将展示简单易懂的方法。 像David Grayson那样在哈希中填充所有内容从长远来看效率要高得多,但是对于几次运行的脚本来说这可能就足够了。

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" 

如果领先的空间是不需要的:

config = CSV.read('config.csv', {:col_sep => ', '})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM