【问题标题】:Importing CSV data into a ruby array/variable将 CSV 数据导入 ruby​​ 数组/变量
【发布时间】:2012-01-17 23:53:30
【问题描述】:

我正在尝试在 SiriProxy 项目的插件中使用 CSV 作为设置文件以使用网络唤醒。本项目基于 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-on-rails ruby csv fastercsv


    【解决方案1】:

    我将演示非常简单的方法。从长远来看,像 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 => ', '})
    

    【讨论】:

    • 这应该是答案,再加上一个——Hash[arr] 的使用会将CSV.read() 的结果——即一个数组数组——转换为一个哈希:Hash[CSV.read('config.csv', col_sep: ', ')]
    【解决方案2】:

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

    【讨论】:

    • 非常感谢!我快到了。你是最棒的
    • 这个解决方案太复杂了; @steenslag 更惯用。我添加了一条注释来说明如何将 CSV.read() 的结果转换为 Hash。
    猜你喜欢
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 2013-08-08
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    相关资源
    最近更新 更多