0

Input file is an excel file and the excel file has headers like author, 2ndauthor, 3rdauthor.

So the input xlsx looks like

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

But currently the ruby on rails program does something like

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

So the output of the ruby program looks like

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

But I want to include 2ndauthor, 3rdauthor,... to get

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

So, comma is added between authors only when there are 3 or more than 3 authors.

Is there any brilliant way to do this?

added question

If

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

was generating

AAA (BB paper)

then will

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

generate

AAA (BB, BBB, and CCC paper)

?

1
  • If you like the answer, please accept it by clicking the check under answer number. Commented Nov 5, 2013 at 4:32

1 Answer 1

1

This code should be close, but I haven't actually run it. It takes advantage of two nice features, the Rails Array::to_sentence and 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
Sign up to request clarification or add additional context in comments.

5 Comments

@Steve_Wilhem Thank you but as I wrote " and " should come just before the last non-empty author, and "," should come just after non-last authors if the total number of authors are 3 or more. I guess your code currently does not take that into consideration?
It should, that is what to_sentence does.
@Steve_Wilhem It should look like DNA (Watson and Crick paper), so it should be like Title (Author and 2ndAuthor paper) Does to_sentence also add parenthesis after "paper" and before the first author?
@Steve_Wilhem What I am asking is essentially about the added question that I wrote. (I appended it to my question.)
My answer was edited to add parentheses around the author/paper section.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.