Ruby array map and join in one loop

Francis Chartrand

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?

tessi

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.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Ruby array map and join in one loop

From Dev

Join each element of one array to each element of other array in ruby

From Dev

How can one loop in a ruby with 2 variables on Array

From Dev

Equivalent of array join() for Set in Ruby?

From Dev

Array join function - Ruby on Rails

From Dev

Map multidimensional array with join as proc

From Dev

Join array items in loop with perl

From Dev

`return` in Ruby Array#map

From Dev

Feed Array of Strings into Ruby Loop

From Dev

Loop through array in Ruby/Rails

From Dev

Decrement the array in ruby using for loop

From Dev

Ruby: map array of strings into array of arrays

From Dev

Loop Through Array and Store as New Array - Ruby

From Dev

How to join two array attributes if the second is != "" in Ruby

From Dev

Map from one object to another in Ruby

From Dev

Ruby map specific hash keys to new one

From Dev

Map from one object to another in Ruby

From Dev

Push array into array on ruby by just one level

From Dev

Break while loop after one execution? Ruby

From Dev

Map a Ruby array of timeseries values to a weighted interval

From Dev

Ruby send method to Array#map

From Dev

Ruby array map not outputting in required form

From Dev

Uniq an array by one column and join another column

From Dev

Ruby - decrease integers from params one by one and loop with those

From Dev

Ruby: Appending hashes to an array in an each loop

From Dev

ruby loop through array and extract elements

From Dev

Reverse an array without using a loop in ruby

From Dev

Trouble with for loop with 2D array in ruby

From Dev

Add to an array from within a loop using Ruby