GhostRider
GhostRider

Reputation: 2170

Checking variables exist before building an array

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?

Upvotes: 1

Views: 44

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110675

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:"

Upvotes: 0

Arup Rakshit
Arup Rakshit

Reputation: 118271

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: "

Upvotes: 1

Mohammad AbuShady
Mohammad AbuShady

Reputation: 42799

It's easier to use interpolation

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

Nils will be substituted as empty strings

Upvotes: 4

Related Questions