简体   繁体   中英

Pull data out of multiple arrays in csv file for ruby

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]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM