1

In my Ruby 2.7 app I want to join an array of strings to have one string separated by commas. As follows:

[company.name, company.street, company.zipcode, company.city]
=> ["Sanford, Reilly and Schmidt", "Hoffmannstr. 186", "84875", "Gebesee"]

Expected result:

["Sanford, Reilly and Schmidt", "Hoffmannstr. 186", "84875 Gebesee"]

Obviously to have such a result I can put an empty string between company.zipcode and company.city and at the end use .join(', ') method like this:

[company.name, company.street, company.zipcode + ' ' + company.city].join(', ')

But honestly this code is smelly for me, is there any better way to achieve the same result?

2
  • 4
    Well one way to make it less "smelly" is do not use + to concatenate Strings. Instead use interpolation [company.name, company.street, "#{company.zipcode} #{company.city}"].join(', ') Commented Jan 6, 2021 at 18:29
  • 2
    The Facets gem has all kinds of interesting methods. Array#conjoin is one of them; it is like join but more powerful. It allows for a second argument (and/or a block): [1,2,3].conjoin(', ', ' and ') # =>"1, 2 and 3" Commented Jan 6, 2021 at 23:50

2 Answers 2

2

Use two join() calls:

[company.name, company.street, [company.zipcode, company.city].join(' ')].join(', ')

This method is preferred if you have non-blank delimiter on which to join and/or an array argument. In your specific case, the solution by engineersmnky using "#{...} #{...}" is shorter and more clear.

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

Comments

1
arr = [company.name, company.street, company.zipcode, company.city]
  #=> ["Sanford, Reilly and Schmidt", "Hoffmannstr. 186", "84875", "Gebesee"]
arr[0..-3] << "%s %s" % arr[-2, 2]
  #=> ["Sanford, Reilly and Schmidt", "Hoffmannstr. 186", "84875 Gebesee"] 

or

arr[0..-3] << arr[-2, 2].join(' ')
  #=> ["Sanford, Reilly and Schmidt", "Hoffmannstr. 186", "84875 Gebesee"] 

arr is not mutated.

Comments

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.