Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining string elements of an array in Ruby

I've got an array that at this point is ["firstname1 ", "lastname1", "firstname2 ", "lastname2", etc], and I'm trying to come up with a way to combine the strings such that I'll have an array of ["firstname1 lastname1", "firstname2 lastname2", etc].

like image 756
samurai_c Avatar asked Dec 15 '22 16:12

samurai_c


1 Answers

Using Enumerable#each_slice, you can iterate slice of n elements (2 in your case).

By joining those two elements, you will get what you want.

a = ["firstname1 ", "lastname1", "firstname2 ", "lastname2"]
a.each_slice(2).map(&:join)
# => ["firstname1 lastname1", "firstname2 lastname2"]
like image 167
falsetru Avatar answered Jan 06 '23 03:01

falsetru