【问题标题】:load csv via ruby into hash then selecting element from hash通过 ruby​​ 将 csv 加载到哈希中,然后从哈希中选择元素
【发布时间】:2012-07-08 11:18:18
【问题描述】:

我今天正在学习 ruby​​,但在从哈希中提取单个元素时遇到了困难。

login1.csv

role,uName,passwd
adm,admin1,a1
mgr,manager,m
user,user1,u1
adm,admin2,a2

红宝石代码

def csvIntoHash
  # load csv Into hash
  $table = []
  File.open("logIn1.csv") do|f|
    columns = f.readline.chomp.split(',')
    until f.eof?
      row = f.readline.chomp.split(',')
      row = columns.zip(row).flatten #build hash from array
      $table << Hash[*row]
    end
  end
end
#
#main
csvIntoHash
#pulls all hash elements when role=mgr
puts $table.select {|rEntry| rEntry["role"]=="mgr"} 

当 role=mgr 时如何仅提取 uName 然后将其分配给变量?

感谢您的帮助。

【问题讨论】:

    标签: ruby csv hash load


    【解决方案1】:

    您应该查看CSV library in Core

    从你这里的CSV格式来看,如果你真的想让它得到经理的uName,我有以下解决方案。

    manager = ""
    CSV.read("file.csv").each_with_index do |arr, index|
      role_column = arr.index("role") if index == 0
      if arr[role_column.to_i] == "mgr"
        manager = arr[role_column.to_i + 1]
      end
    end
    

    编辑:
    显然,这是假设 CSV 表中只有一位经理。如果需要,您可以修改代码以分配一组经理。

    【讨论】:

      【解决方案2】:

      select() 返回一个数组,因此请查看第一个(仅在您的情况下?)条目,它是您构建时的哈希:

      mgrh = $table.select {|rEntry| rEntry["role"]=="mgr"}
      mgr_role = mgrh.first["uName"] # => "manager"
      

      【讨论】:

        猜你喜欢
        • 2014-02-17
        • 1970-01-01
        • 2018-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-03
        • 1970-01-01
        相关资源
        最近更新 更多