2014-01-24 27 views
0

我試圖通過使用CSV文件格式將一些批量的數據插入到表中的特定列。我的代碼如下:條件中的字符串文字

代碼

def maritalstatus_migration 
    filename = "#{RAILS_ROOT}/config/MaritalStatus_Data_Migration_240114.csv" 
    file=File.new(filename,"r") 
    while (line = file.gets) 
     columns = line.split("$") 
     employee = Employee.find_by_employeeid(columns[0].to_s.chomp.strip) 
     personnel = Personnel.find_by_extid(columns[0].to_s.chomp.strip) 
     if employee && personnel 
     sheet_marital_status = columns[1].to_s.chomp.strip 
     if sheet_marital_status == 'Married' or 'MARRIED' 
      personnel.marital_status = 'Married' 
     elsif sheet_marital_status == 'Unmarried' or 'UNMARRIED' 
      personnel.marital_status = 'Unmarried' 
     elsif sheet.marital_status ='Unknown' or 'UNKNOWN' 
      personnel.marital_status = 'Unknown' 
     else 
      personnel.marital_status = columns[1].to_s.chomp.strip 
     end 
     end 
    end 
end  

當我在控制檯上運行我的方法,我得到一個警告說:

String literal in condition 

指着線personnel.marital_status = columns[1].to_s.chomp.strip,我算什麼我做錯了。任何建議將不勝感激。

回答

1

一個修正尤其是在你使用OR條件應靜音警告

if ['Married','MARRIED'].include?(sheet_marital_status) 
personnel.marital_status = 'Married' 
elsif ['Unmarried','UNMARRIED'].include?(sheet_marital_status) 
personnel.marital_status = 'Unmarried' 
elsif ['Unknown','UNKNOWN'].include?(sheet_marital_status) 
personnel.marital_status = 'Unknown' 
else 
personnel.marital_status = columns[1].to_s.chomp.strip 
end 

因爲如果你使用'XXX' or 'xxx',其計算結果始終爲「XXX」的代碼。這意味着您只將sheet_marital_status與第一個字符串進行比較。這可能是編譯器警告指出的。你最好使用Include。

lemme也知道你的發現。

+0

這是完美的!謝謝。 – Pavan

+0

感謝您的更正@Pavan –

0

String literal in condition警告來得光彩啦起來,當你通過String類的實例作爲條件if操作,即例如,x or y,其中x布爾(正確的),並yString(不正確) 。讓我們看到了一種導致警告的條件的行爲:

if false or "ww12" 
    p 1 
end 

# warning: string literal in condition 
1 
=> 1 

正如你所看到的,字符串字面條件總是被評估爲true。所以對於大多數情況下,它可以被視爲語法錯誤。

爲了解決它只是將String轉換成布爾,如x == 'string'。而對於你的代碼,你會得到:

if sheet_marital_status == 'Married' or sheet_marital_status == 'MARRIED' 
    ... 
end 

或與優化:

if sheet_marital_status =~ /^married$/i 
    ... 
end 

注:對於你的情況,這將是最好使用你case/when聲明,而不是if-elsif-else聲明,因爲你在樹上有同質的情況。

1

我會使用一個case聲明:

personnel.marital_status = case columns[1].to_s.chomp.strip 
          when 'Married', 'MARRIED' 
          'Married' 
          when 'Unmarried', 'UNMARRIED' 
          'Unmarried' 
          when 'Unknown', 'UNKNOWN' 
          'Unknown' 
          else 
          columns[1].to_s.chomp.strip 
          end 
+0

謝謝!酷一個。 – Pavan