arraysrubyflattennomethoderror

Why am I getting "undefined method `flatten'" when calling on an array?


Problem

I am building a script that takes in a column from a CSV that can contain 0 or more ID numbers. I have created an array of the column, however, since some cells have no ID number and some have multiple,I have an array of arrays.

I want to create an array where each element is a single ID (i.e split the IDs from each element in the array to a single element).

Here is my code so far:

require 'csv'
class MetadataTherapyParser

    def initialize (csv)
        @csv = csv
    end

    def parse_csv
        therapy_array = []
        CSV.foreach(@csv) do |csv_row|
            therapy_array << csv_row[0] 
        end
    end

    def parse_therapies(therapy_array) 
        parsed_therapy_array = therapy_array.flatten!
        puts parsed_therapy_array   
    end
end

metadata_parse = MetadataTherapyParser.new ("my_csv_path")
metadata_parse.parse_csv
metadata_parse.parse_therapies(metadata_parse)

Actual Results

I am getting the following error:

in `parse_therapies': undefined method `flatten' for #<MetadataTherapyParser:0x00007fd31a0b75a8> (NoMethodError)

From what I can find online, flatten is the method to use. However I can't seem to figure out why I am getting an undefined method error. I have checked to ensure that therapy_array is indeed an array.

If anyone has encountered this issue before and could offer some advice, it would be greatly appreciated!

Thank you in advance.


Solution

  • While calling the method parse_therapies instead of passing an array you are passing the metedata_parse, which is an object of MetadataTherapyParser

    Try this:

    def parse_csv
        therapy_array = []
        CSV.foreach(@csv) do |csv_row|
            therapy_array << csv_row[0] 
        end
        therapy_array
    end
    

    Then while calling the methods:

    metadata_parse = MetadataTherapyParser.new ("my_csv_path")
    therapy_array = metadata_parse.parse_csv
    metadata_parse.parse_therapies(therapy_array)
    

    This should pass an Array instead of MetadataTherapyParser object to your parse method.