0

I want to replace an item in an array:

arr = ["55", "4.ARTHUR", "masddf"]

with potentially multiple items based on whether it matches a regular expression. I would like to have the result:

["55", "4.", "ARTHUR", "masddf"]

I tried:

arr.map { |o| o =~ /\d+\./ ? o.split(/^(\d+\.)/).reject { |c| c.empty? } : o }
# => ["55", ["4.", "ARTHUR"], "masddf"]

arr.map { |o| o =~ /\d+\./ ? o.split(/^(\d+\.)/).reject { |c| c.empty? }.flatten : o }
# => ["55", ["4.", "ARTHUR"], "masddf"]

I can't seem to get the elements outside of the array they got split into. Any ideas?

1 Answer 1

3

Use flat_map instead:

arr = ["55", "4.ARTHUR", "masddf"]
arr.flat_map { |o| o =~ /\d+\./ ? o.split(/^(\d+\.)/).reject { |c| c.empty? } : o }
# => ["55", "4.", "ARTHUR", "masddf"]

See it on repl.it: https://repl.it/F90V

By the way, a simpler way to solve this problem is to use String#scan:

arr.flat_map {|o| o.scan(/^\d+\.|.+/) }

See it on repl.it: https://repl.it/F90V/1

Sign up to request clarification or add additional context in comments.

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.