CD-RUM CD-RUM - 4 years ago 124
Ruby Question

Array of strings and hashes: flatten to make one dimensional

If I have an array that looks like this:

['one', { 'two' => 'three' }, 'four']


How can I get it to:

['one', 'two, 'three', 'four']


Things like
.flatten
and
.flat_map
don't remove the inner hashes.

Answer Source

I think the closest solution you are going to get is something on the lines of:

['one', { 'two' => 'three' }, 'four'].
  flat_map {|f| f.respond_to?(:flatten) ? f.flatten : f }

I prefer the #respond_to? as it's generally better to check if it quacks like a duck, not if it is a duck.

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