2014-01-24 31 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