Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

Ruby join array of strings with space between last two elements

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...