CSV Parse: search a value in a certain column and print out the whole row that contains it
So, I already made a similar question a few days back that got me very close to figuring it out. I wanted a system that'd take the user input and search it through an specific column and, when found, would print the entire row the column was in. I already defined the method that'll search through the .csv, however, it's still not working as intended. The exact error is:
undefined method `include?' for nil:NilClass (NoMethodError)
I've viewed and reviewed the .csv, tried out solutions that I found for the same problem, but none seem to work.
data.csv looks like this:
Name;Age;Gender Edward;21;Male Michael;21;a Sarah;22;a
As you can see, I use "
a" so that I don't use a blank space.
Also, I used
:col_sep => ";" in the code to avoid further errors (it's too big to change every semicolon into a comma manually).
I really don't know what else to do at this point, I understand the problem, but I can't find the solution.
This is what my code looks like:
require 'csv' def find_row_in_csv(file_path, column_name, search_value) CSV.foreach(file_path, headers: true, :row_sep => "\r\n", :col_sep => ";").find do |row| row[column_name].include?(search_value) end end search_value = gets.chomp.to_s matching_row = find_row_in_csv('data.csv', "Name", search_value) p matching_row
I used that
:row_sep => "\r\n" because I was getting a malformed CSV error, but now that I fixed that, it appears as though I haven't defined the
include? method for NilClass (NoMethodError), which I don't understand since there's no blank values in the .csv.
I thought it'd work as is, since I pretty much copied it from the best response I got, but I've been stuck with this for a few days now.