0

输入文件是一个 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)

?

4

1 回答 1

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
于 2013-11-02T08:18:48.653 回答