简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM