Dave Dave - 4 years ago 130
Ruby Question

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

I'm using Ruby 2.4. I want to replace an item in an array with potentially multiple items, based on whether it matches a regular expression. The problem is, I can't seem to get the elements outside of the array they got split into. So I tried ...

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


but what I would like is instead of having the result be

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


I get

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


Any ideas?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download