0

How do I parse through a csv file to check if a value exists in all the array in the csv file? And after just pull the array that contains the value and display it?

     require 'csv'

########
## Ask for Serial number
########
serial_number = ask("Product serial number?", true)
serial_number = serial_number.to_s
serial_number = serial_number.upcase
stamp_date= Time.now
old = Time.now.to_i

###################
## CHECK if SN exist in Serial List
###################

CSV.foreach('procedures/Serial.csv') do |row|
    check_serial = row[0]
7
  • 1
    What exactly are you having trouble with? You need to load the CSV, iterate through the rows, search for the value in each row, and display the rows that match. Are you confused about all of these stages? Have you tried anything? Commented May 31, 2018 at 20:05
  • Yes, require 'csv', then use the CSV class. Better you if can share some code if still stuck. Commented May 31, 2018 at 20:11
  • You parse a csv with CSV.parse. You check if a value exists with methods like ==, or Array#include? (your description is somewhat unclear). You "pull the value that contains it" (??) with methods like Enumerable#select or Enumerable#find. There is insufficient information in your question for anyone to provide a full code sample, and you haven't shared any attempted solution - so I really don't know what answer you're looking for? Commented May 31, 2018 at 20:13
  • Not sure what to do after reading through the csv file Commented May 31, 2018 at 20:55
  • @TomLord I have created this so far Commented May 31, 2018 at 20:58

1 Answer 1

1

Let's say you have this csv file:

# starships.csv
serial_number,ship_name,speed
NCC-1701,USS Enterprise,Warp 8
NCC-74656,USS Voyager,Warp 9.975

For example, you can lookup at serial number this way:

require 'csv'

CSV.foreach('starships.csv', headers: true) do |row|
  p row['ship_name'] if row['serial_number'] == "NCC-74656"
  # whatever code
end

#=>"USS Voyager"

I do not know the first part of your code, but the second is missing the end of the iteration loop. If you set headers: true, the first line is skipped as data and is used to build access keys, allowing you to use row['ship_name'] instead of row[0], for example.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.