Simon Ninon
Simon Ninon

Reputation: 2441

Join array elements depending on the element's index

I have this array: [ 'here', 'are', 'some', '123', 'data' ]. I would like to join the elements before the '123' into a string and the elements after the '123' into another string to get these three strings:

I get the index of '123' by arr.index {|el| el =~ /\d{3}/ }. I tried join method, but I didn't find a way to add some conditions. I developed a solution using array.each { ... } to manually join the elements. What is the best way to do it?

Upvotes: 1

Views: 3258

Answers (3)

McGar
McGar

Reputation: 205

b = a.index {|el| el =~ /\d{3}/}
s = [a[0..b-1].join(" "),a[b],a[b+1..a.size-1].join(" ")]

So s[0], s[1], s[2] will be the 3 strings. Is this what you are looking for?

Upvotes: 1

sawa
sawa

Reputation: 168101

arr.chunk{|e| (e =~ /\d{3}/) || false}.map{|a| a.last.join(" ")}
# => ["here are some", "123", "data"]

Upvotes: 2

Matt
Matt

Reputation: 20786

arr = [ 'here', 'are', 'some', '123', 'data' ]
i = arr.index {|el| el =~ /\d{3}/ }

arr[0..i-1].join(' ') # => here are some
arr[i] # => 123
arr[i+1..-1].join(' ') # => data

Upvotes: 2

Related Questions