1

I am generating a string from a number of components (title, authors, journal, year, journal volume, journal pages). The idea is that the string will be a citation as so:

@citation = article_title + " " + authors + ". " + journal + " " + year + ";" + journal_volume + ":" + journal_pages 

I am guessing that some components occasionally do not exist. I am getting this error:

no implicit conversion of nil into String 

Is this indicating that it is trying to build the string and one of the components is nil? If so, is there a neat way to build a string from an array while checking that each element exists to circumvent this issue?

1
  • 1
    if doesn't exist what you want to output ? Commented Mar 22, 2015 at 16:43

3 Answers 3

4

It's easier to use interpolation

@citation = "#{article_title} #{authors}. #{journal} #{year}; #{journal_volume}:#{journal_pages}" 

Nils will be substituted as empty strings

Sign up to request clarification or add additional context in comments.

1 Comment

This works beautifully. Many thanks. Will accept when the timer allows me too....cheers Pal.
1
array = [ article_title, authors ,journal, year, journal_volume, journal_pages ] @citation = "%s %s. %s %s; %s:%s" % array 

Use String#% format string method.

Demo

>> "%s: %s" % [ 'fo', nil ] => "fo: " 

1 Comment

This also works but for reasons I haven't explained above, the solution of Mohammad AbuShady fits better with my needs. Many thanks Arup.
0

Considering that you presumably are doing this for more than one article, you might consider doing it like so:

SEPARATORS = [" ", ". ", " ", ";", ":", ""] article = ["Ruby for Fun and Profit", "Matz", "Cool Tools for Coders", 2004, 417, nil] article.map(&:to_s).zip(SEPARATORS).map(&:join).join # => "Ruby for Fun and Profit Matz. Cool Tools for Coders 2004;417:" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.