Ruby on Rails简单的输出样式修复

时间:2013-11-02 07:39:54

标签: ruby-on-rails ruby

输入文件是excel文件,excel文件包含author,2ndauthor,3rdauthor等标题。

所以输入xlsx看起来像

Title    Author     2ndAuthor     3rdAuthor    4thAuthor
E=MC^2   Einstein
DNA      Watson     Crick
AAA      BB         BBB           CCC

但目前ruby on rails程序就像

一样
if not contents["#{record.title} (#{record.author} paper)"]
  contents += "*[[#{record.title} (#{record.author} paper)]]\r\n"
end

所以ruby程序的输出看起来像

E=MC^2 (Einstein paper)
DNA (Watson paper)
AAA (BB paper)

但我想包括2ndauthor,3rdauthor,...来获取

E=MC^2 (Einstein paper)
DNA (Watson and Crick paper)
AAA (BB, BBB, and CCC paper)

因此,只有当有3位或3位以上的作者时,才会在作者之间添加逗号。

有没有什么好方法可以做到这一点?

添加了问题

如果

"#{title} (#{author} paper)"

正在生成

AAA (BB paper)

然后

"#{title}" + " ([#{author},#{2ndauthor},#{3rdauthor},#{4thauthor}].delete_if{|val| val.nil?}.to_sentence" + " paper)"

产生

AAA (BB, BBB, and CCC paper)

1 个答案:

答案 0 :(得分:1)

此代码应该很接近,但我实际上并没有运行它。它利用了两个不错的功能,Rails Array :: to_sentence和Ruby Array :: delete_if

# code assumes record member names are the same as input xlsx
# change if otherwise. 
# code also assume blank columns will be nil in record. If not, change delete_if block
# accordingly
# also assume there is some array of records

contents = ""
records.each do |record|
    contents += "\r\n" if contents != ""
    contents += "#{record.Title} (#{[record.Title, record.Author, record.2ndAuthor, record.3rdAuthor, record.4thAuthor].delete_if{|val| val.nil?}.to_sentence}) paper"
end