For:
a = [ ["John", "Doe"], ["Sue", "Smith"]]
The desired output is: "John Doe, Sue Smith"
The brute-force code is easy:
a = [ ["John", "Doe"], ["Sue", "Smith"]]
name_array = []
a.each { |n| name_array << n.join(" ") } # first, inner join w/ space
s = name_array.join(", ") # then, outer join with comma
But is there a more succint (one-liner?) to accomplish this in Ruby?
a = [["John", "Doe"], ["Sue", "Smith"], ["Melba", "Jones"]]
The obvious way of doing this, that has been mentioned by others, is:
a.map { |arr| arr.join(' ') }.join(', ')
#=> "John Doe, Sue Smith, Melba Jones"
As an exercise, here are three ways this can be done without using Array#map
Use Enumerable#reduce (aka inject
)
a.drop(1).reduce(a.first.join(' ')) { |s,name| s + ", %s %s" % name }
#=> "John Doe, Sue Smith, Melba Jones"
Use recursion
def doit((name, *rest))
rest.empty? ? name.join(' ') : "%s %s, %s" % [*name, doit(rest)]
end
doit(a)
#=> "John Doe, Sue Smith, Melba Jones"
Flatten, join with a space, use String#gsub to insert commas
r = /
\w+[ ]\w+ # match two words separated by a space
(?=[ ]) # positive lookahead asserts that next character is a space
\K # reset start of match to current location and discard all
# previously matched characters from match that is returned
/x # free-spacing regex definition mode
a.flatten.join(' ').gsub(r, ',')
#=> "John Doe, Sue Smith, Melba Jones"
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments