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)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments