2

I want to do different iteration to elements in single array.

arr = ["1111", "2221", "7ext", "3345"] 

I want to run a block that would slice only the element that contains letters and elements with no letter remain the same. The result would be following

arr = ["1111", "2221", "7", "e", "x", "t", "3345"] 

I do not know neither how many elements would be in array or order. All elements are strings.

1
  • Your result is invalid. Commented Aug 22, 2015 at 11:02

2 Answers 2

3
arr.flat_map{|s| s.split(/([a-z])/i)}.reject(&:empty?) # => ["1111", "2221", "7", "e", "x", "t", "3345"] 
Sign up to request clarification or add additional context in comments.

Comments

3

Try this:

arr = ['1111', '2221', '7ext', '3345'] arr.flat_map { |e| e =~ /\D/ ? e.split('') : e } # => ["1111", "2221", "7", "e", "x", "t", "3345"] 

2 Comments

You can eliminate flatten by using flat_map. Aside: one of my sons lives near Cali (Lake Calima).
@CarySwoveland thanks, great suggestion - and BTW: Cali is called "Heaven's outpost" for a good reason :) I'm glad for your son, cheers!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.