我有一个字符串与额外的空格:
First,Last,Email,Mobile Phone,Company,Title,Street,City,State,Zip,Country,Birthday,Gender,Contact Type
我想解析这行并删除空格.
我的代码看起来像:
namespace :db do task :populate_contacts_csv => :environment do require 'csv' csv_text = File.read('file_upload_example.csv') csv = CSV.parse(csv_text,:headers => true) csv.each do |row| puts "First Name: #{row['First']} \nLast Name: #{row['Last']} \nEmail: #{row['Email']}" end end end
解决方法
你可以首先剥离你的哈希:
csv.each do |unstriped_row| row = {} unstriped_row.each{|k,v| row[k.strip] = v.strip} puts "First Name: #{row['First']} \nLast Name: #{row['Last']} \nEmail: #{row['Email']}" end
编辑也可以去散列键