4

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].

2 Answers 2

11

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"]
Sign up to request clarification or add additional context in comments.

Comments

1

Some other ways:

a = ["Shirley ", "Temple", "Oliver ", "Hardy", "John ", "Wayne"]

#1

(0...a.size).step(2).map { |i| a[i]+a[i+1] }
  #=> ["Shirley Temple", "Oliver Hardy", "John Wayne"]

#2

enum = a.to_enum
(a.size/2).times.map { enum.next + enum.next }
  #=> ["Shirley Temple", "Oliver Hardy", "John Wayne"]

#2a

enum = a.to_enum
names = []
loop { names << enum.next + enum.next }
names
  #=> ["Shirley Temple", "Oliver Hardy", "John Wayne"]

#3

fname = nil
a.each_with_object([]) { |s,a| (s[-1]==' ') ? fname=s : a << fname+s }
  #=> ["Shirley Temple", "Stan Laurel", "John Wayne"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.