Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby array map and join in one loop

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?

like image 762
Francis Chartrand Avatar asked Mar 23 '23 05:03

Francis Chartrand


2 Answers

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)
like image 195
tessi Avatar answered Apr 05 '23 22:04

tessi


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.

like image 29
Cary Swoveland Avatar answered Apr 05 '23 22:04

Cary Swoveland