如何使用Table.delete_if()

时间:2016-03-25 00:13:36

标签: ruby csv

我正在阅读csv文件

require 'csv'

recipients = CSV.read('recipients.csv', headers: true)

found = []
if User.find_by(email: recipients['email'])
  found << recipients['email']
end

table = CSV.table('recipients.csv')

table.delete_if do |t|
  found.each { |f| t['email'] == f['email']}
end


CSV.open('/tmp/users.csv', 'wb') do |w|
  w << found.to_csv
end

以下一行:found.each { |f| t['email'] == f['email']} 结果

TypeError: no implicit conversion of String into Integer from lib/scripts/foo.rb:13:in []&#39;`

很明显,我不知道如何使用delete_if以及如何在这种情况下解决类型不匹配问题。 所以,非常感谢帮助。

1 个答案:

答案 0 :(得分:0)

行号13

中的

  found.each { |f| t['email'] == f['email']}

fArray的一个实例,您正在尝试将String作为索引传递,因此可能会发生这种情况。

解释

 > a=[]
 => [] 
2.2.1 :015 > a['email']
TypeError: no implicit conversion of String into Integer
    from (irb):15:in `[]'
 > a=['email', 'ram']
 => ["email", "ram"] 
2.2.1 :018 > a['email']
TypeError: no implicit conversion of String into Integer
    from (irb):18:in `[]'