要從CSV文件中獲取數據到紅寶石,請嘗試以下操作:
# This will read the data in with headers, convert the column names to symbols,
# and then turn each resulting CSV::Row instance into a hash
data = CSV.read('temp.csv', headers: true, header_converters: :symbol).map(&:to_h)
這應該返回以下內容:
=> [{:id=>"SD0005", :required=>" yes"}, ...]
一旦你有你所有的信息在格式,你可以在Ruby中使用,你可以創建一個方法來檢查每個ID的有效性。
def valid_id?(id_string)
# uses Regular Expressions to ensure ID is 6
# characters that consist of only numbers/letters
# The double-bang(!!) turn a truthy value to `true`
# or false value to `false`
!!id_string.match(/^[\D|\d]{6}$/)
end
如果您想測試另一列的有效性,請使用單獨的方法進行測試。
def valid_required?(req_column)
req_column.downcase == 'yes' || req_column.downcase == 'no'
end
創建主驗證方法
def all_valid?(row)
valid_id?(row[:id]) && valid_required?(row[:required])
end
然後只保留一個ID爲有效
# #select keeps values whose block evaluates to `true`
valid_records = data.select { |record| all_valid?(record) }
你需要紅寶石處理的記錄。爲什麼你會在JavaScript中有驗證碼? –
編輯問題 –