Dave
Dave

Reputation: 19120

How do I replace one element in an array with potentially multiple elements?

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?

Upvotes: 0

Views: 128

Answers (1)

Jordan Running
Jordan Running

Reputation: 106027

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

Upvotes: 3

Related Questions