Ruby noob在这里。我只想在我的ERB文件中使用@next_name来显示数组中的下一个文件名。 @prev_name工作正常,但@next_name字段为空。我做错了什么?
require 'csv'
require 'erb'
class Thing
def initialize
@prev_name = prev_name
@next_name = next_name
end
template = File.read "workstemplate.erb"
erb_template = ERB.new template
array = Array.new
CSV.foreach("works_list.csv", :headers =>true) do |row|
fileName = row['fileName']
title = row['title']
description = row['description']
description.tr('"', '')
array << fileName
array.each_with_index do |a, i|
if i> 0 && i< array.size
@prev_name = array[i-1]
@next_name = array[i+1]
else
@prev_name == 0
@next_name == 0
end
end
work_template = erb_template.result(binding)
Dir.mkdir("output") unless Dir.exists? "output"
filename = "#{fileName}.html"
File.open(filename,'w') do |file|
file.puts work_template
end
end
end
答案 0 :(得分:1)
问题是您使用CSV.foreach
,每个周期取一行;为了获得@next_name
的值,您应该使用预取每个CSV行的内容,例如f.e. CSV.read
:
CSV.read("works_list.csv", :headers =>true).each do |row|
...