Array exemple
[
 [
   "Francis",
   "Chartrand",
   "[email protected]"
 ],
 [
   "Francis",
   "Chartrand",
   "[email protected]"
 ],...
]
Result wanted
"[email protected], [email protected], ..."
My solution (two loop)
array.map{|a| a[2]}.join(", ")
Is it possible to do this with one loop?
Using Enumerable#inject we can do the task in one loop:
a = [
  ["Francis", "Chartrand", "[email protected]"],
  ["Francis", "Chartrand", "[email protected]"]
]
a.inject(nil) {|str, arr| str ? (str << ', ' << arr[2]) : arr[2].dup}
#=> "[email protected], [email protected]"
However, this is an academic thing only, because map/join is faster and more readable anyways. See this benchmark:
             user   system    total       real
map/join 1.440000 0.000000 1.440000 ( 1.441858)
inject   2.220000 0.000000 2.220000 ( 2.234554)
                        Here's one approach, but it may not be especially fast.
s = ''          
array.flatten.each_slice(3) {|e| s += e.last + ', '} 
s.chop.chop
Here's another:
array.transpose[2].join(', ')
I assume you wanted a single string of email addresses for the entire array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With