2

I have an array containing of subarrays like this:

arr = [[{"big" => "2055", "small" => -"-10", "thin" => "i"},
        {"big" => "2785", "small" => "0", "thin" => "l"}], 
       [{"big" => "7890", "small" => "3", "thin" => "t"},
        {"big" => "2669", "small" => "0,5", "thin" => "f"},
        {"big" => "9000", "small" => "2", "fat" => "O"}]]

I want to add subarrays to itself to get an array like this:

arr = [{"big" => "2055", "small" => "-10", "thin" => "i"},
       {"big" => "2785", "small" => "0", "thin" => "l"},
       {"big" => "7890", "small" => "3", "thin" => "t"},
       {"big" => "2669", "small" => "0,5", "thin" => "f"},
       {"big" => "9000", "small" => "2", "fat" => "O"}]

Doing like this:

arr.map! {|x| x+x}

I get added subarrays but every hash appears twice. How to do it right?

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
mia102aim
  • 103
  • 1
  • 7

4 Answers4

0

Do you just want to flatten the array?

arr.flatten

It concatenates every sub-array into one big array, recursively if needed.

[[1,2], [3,4]].flatten
# => [1, 2, 3, 4]

If you want to modify the array in place, you can use :

arr.flatten!

It doesn't matter what the inner-elements look like (integers, strings, hashes), as long as they're not arrays, they won't be touched by flatten.

Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
0

Ruby have a built in method try use Array.flatten

Chen Kinnrot
  • 20,609
  • 17
  • 79
  • 141
0

You can use flatten!:

arr.flatten!

#=> [{"big"=>"2055", "small"=>"-10", "thin"=>"i"},
     {"big"=>"2785", "small"=>"0", "thin"=>"l"},
     {"big"=>"7890", "small"=>"3", "thin"=>"t"},
     {"big"=>"2669", "small"=>"0,5", "thin"=>"f"},
     {"big"=>"9000", "small"=>"2", "fat"=>"O"}]
Gerry
  • 10,337
  • 3
  • 31
  • 40
0

You can try this

arr = arr.flatten
Son Nguyen
  • 170
  • 3
  • 6