将数组存储到Csv:<<<':undefined methodmap'for“Coco”:String

时间:2018-05-22 15:23:03

标签: ruby

我试图将allocine网页作为一个练习,我可以获得电影标题,但我无法将它们存储到csv文件中。

require 'open-uri'
require 'nokogiri'
require 'csv'

url = "http://www.allocine.fr/film/meilleurs/"

html_file = open(url).read
html_doc = Nokogiri::HTML(html_file)
array = []

html_doc.search('.no_underline').each do |element|
    array << element.text.strip
end

puts array

csv_options = { col_sep: ',', force_quotes: true, quote_char: '"' }
filepath    = 'allocine.csv'

CSV.open(filepath, 'wb', csv_options) do |csv|
  array.each  { |item| csv << item }
end

这是我的错误消息:Coco 阿甘 La Ligne verte 你的名字 La Liste de Schindler 12 hommesencolère 狮子 Le Parrain 被解放的姜戈 Tu ne tueras指向 黑暗骑士,Le Chevalier Noir 格兰都灵 Le Seigneur des anneaux:le retour du roi 低俗小说 LesEvadés Le Seigneur des anneaux:lacommunautédel'anneau 搏击俱乐部 Le Roi Lion 最伟大的表演者 Le Seigneur des anneaux:les deux之旅 Vol au-dessus d'un nid de coucou Les Enfants Loups,Ame&amp;雪 AuRevoirLà-haut 星际 角斗

/Users/laburthe/.rbenv/versions/2.4.3/lib/ruby/2.4.0/csv.rb:1705:in <<': undefined method map'for“Coco”:String(NoMethodError) 你的意思是?龙头     来自scrap.rb:22:in block (2 levels) in <main>' from scrap.rb:22:in each'     来自scrap.rb:22:在block in <main>' from /Users/laburthe/.rbenv/versions/2.4.3/lib/ruby/2.4.0/csv.rb:1299:in打开'     来自scrap.rb:21:在''

1 个答案:

答案 0 :(得分:0)

你的csv对象不接受字符串,因为它确实需要一个代表整行/行的数组。

所以,也许这就是你想要的

CSV.open(filepath, 'wb', csv_options) do |csv|
  array.each  { |item| csv << [item] }
end