Bastien Bastien - 11 months ago 40
Ruby Question

Ruby merging items in array conditionnally

I have an array containing capital and small letters. I am trying to concatenate capital letters with the following small letters in a new array. For example, I have the following array

first_array = ["A","b","C","d","e"]

and I want to obtain the following array

["Ab","Cde"] #new array

I am trying to iterate through the first array with a code that looks like this:

new_array = []
first_array.each_with_index do |a,index|
if (a!~/^[a-z].*$/)
new_array = new_array.push "#{a}"
new_array[-1] = first_array[index-1] + "#{a}" #the idea is to concatenate the small letter with the previous capital letter and replace the last item in the new array

but it does not work. I am not sure I am tackling this issue efficiently which is why I can't resolve it. Could somebody suggest some options? Thanks.


So, you want to split your original array when next char is uppercase, and then make strings of those subarrays? There's a method in standard lib that can help you here:

first_array = ["A","b","C","d","e"]
result = first_array.slice_when do |a, b|
  a_lower = a.downcase == a
  b_upper = b.upcase == b
  a_lower && b_upper

result # => ["Ab", "Cde"]