简体   繁体   中英

load csv via ruby into hash then selecting element from hash

I am learning ruby today and got stuck with extracting single element from the hash.

login1.csv

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

ruby code

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"} 

How do i extract only the uName when role=mgr then assign it to a variable?

Thanks for any assistance.

select() returns an Array, so look at the first (only, in your case?) entry, which is a Hash as you constructed it:

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

You should look into the CSV library in Core

From the format of your CSV on here, if what you really want it to get the uName of the manager, I have the following solution.

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

EDIT:
Obviously this assums there is only one manager in the CSV sheet. You can modify the code to assign an array of managers if so required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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