Question

Array exemple

[
 [
   "Francis",
   "Chartrand",
   "email@email.com"
 ],
 [
   "Francis",
   "Chartrand",
   "second_email@email.com"
 ],...
]

Result wanted

"email@email.com, second_email@email.com, ..."

My solution (two loop)

array.map{|a| a[2]}.join(", ")

Is it possible to do this with one loop?

Was it helpful?

Solution

Using Enumerable#inject we can do the task in one loop:

a = [
  ["Francis", "Chartrand", "email@email.com"],
  ["Francis", "Chartrand", "second_email@email.com"]
]
a.inject(nil) {|str, arr| str ? (str << ', ' << arr[2]) : arr[2].dup}
#=> "email@email.com, second_email@email.com"

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)

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top