我有一個表,每行增加值(下面代碼中的年份)。 我有一個目標,指定一個「閾值」。目標是用戶定義的,它可以包含表格的一個或多個列的值。這意味着你永遠不會知道目標中指定了多少列。 我想匹配表中的第一行,其中行中的值大於目標中的值。我目前有這樣的:根據用戶定義的輸入構建動態if語句
class Target < ActiveRecord::Base
def loop_sheets(sheets, year_array)
result = nil
elements = self.class.column_names[1..-3].map(&:to_sym)
to_match = elements.select{|e| self.send(e) != nil }
condition = to_match.map do |attr|
"row[:#{attr}] > #{attr}"
end.join " and "
year_array.each do |year|
sheets.each do |sheet|
row = sheet.calculation.datatable.select { |r| r[:year] == year }.first
does_match = eval(condition)
if does_match
result = {
:year => row[:year],
:sheet_name => sheet.name
}
return result
end
end
end
return result
end
end
這很好用,但現在算法固定使用AND匹配。我想支持OR匹配以及AND匹配。另外我想避免使用eval,必須有更優雅的方式。我也想盡可能地減少這段代碼的複雜性。 我如何重寫這段代碼以滿足這些要求?任何建議表示讚賞。
感謝這一點,它實現了所有要求和更多。我會試一試。 –