【发布时间】: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 然后将其分配给变量?
感谢您的帮助。
【问题讨论】: