我想根据两个条件返回一个特定的单元格值。用Ruby解析CSV数据
逻辑:
If ClientID = 1 and BranchID = 1, puts SurveyID
使用Ruby 1.9.3,我想基本上是通过一个excel文件和位于ClientID
和BranchID
柱内的两个具体数值看,在返回相应的值SurveyID
栏。
这是我到目前为止,我在我的在线搜索中找到的。它似乎有希望的,但没有运气:
require 'csv'
# Load file
csv_fname = 'FS_Email_Test.csv'
# Key is the column to check, value is what to match
search_criteria = { 'ClientID' => '1',
'BranchID' => '1' }
options = { :headers => :first_row,
:converters => [ :numeric ] }
# Save `matches` and a copy of the `headers`
matches = nil
headers = nil
# Iterate through the `csv` file and locate where
# data matches the options.
CSV.open(csv_fname, "r", options) do |csv|
matches = csv.find_all do |row|
match = true
search_criteria.keys.each do |key|
match = match && (row[key] == search_criteria[key])
end
match
end
headers = csv.headers
end
# Once matches are found, we print the results
# for a specific row. The row `row[8]` is
# tied specifically to a notes field.
matches.each do |row|
row = row[1]
puts row
end
我知道代码的最后位以下matches.each do |row|
是无效的,但我离开它,希望它会是有意义的其他人。
我该怎么写puts surveyID if ClientID == 1 & BranchID == 1
?
这工作完美。谢谢您的帮助! – Luigi