Ruby: how to push to a hash inside an array on a CSV -
i m new ruby. have 2 csv files, m using 'csv' library. can arrays csvs dont know how push hash inside first csv.
i these 2 arrays csvs:
csv1 = [1,2,{3 => :a},4] csv2 = [5,6,{7 => :b},8]
and want first csv file this:
[1,2,{3 => :a, 7 => :b},4]
this 1 way.
arr1 = [1,2,{ 3 => 'a' },4] arr2 = [5,6,{ 7 => 'b' },8] arr1.map |e| case e when hash e.merge(arr2.select { |e| e.is_a? hash }.first) else e end end #=> [1, 2, {3=>"a", 7=>"b"}, 4]
when
e #=> { 3 => 'a' } h2 = arr2.select { |e| e.is_a? hash }.first #=> [{ 7 => 'b' }].first # { 7 => 'b' } e.merge(arr2.select { |e| e.is_a? hash }.first) e.merge(h2) #=> { 3 => 'a' }.merge({ 7 => 'b' }) #=> {3=>"a", 7=>"b"}
Comments
Post a Comment