代码之家  ›  专栏  ›  技术社区  ›  Pi Horse

Rails:无法将Regexp转换为Integer

  •  0
  • Pi Horse  · 技术社区  · 13 年前

    我的轨道控制器中有以下代码:

    @main_mastertest = $connection.execute("SELECT * FROM builds;")
    
    @l2_tmp_mastertest = Array.new
    @l2_tmp_mastertest = @main_mastertest.map {|y|[y[0]]}
    
    @l2_mastertest = Array.new
    @l2_mastertest = @l2_tmp_mastertest.inject(Hash.new(0)) { |hash,element|
    hash[element] +=1
    hash }
    
    @l2_mastertest = @l2_mastertest.sort_by { |x, _| x }.reverse
    

    在那之后,我试着在我看来做这样的事情:

    <% @l2_mastertest.each_with_index do |row1, index1| %> 
       <% @l2_mastertest.each_with_index do |row2, index2| %> 
           <% if row2[0][ /(\d+\.\d+)/ ].to_s == row1[0].to_s %>      # LINE X
             ..................
           <% end %>
       <% end %>
    <% end %>
    

    但它在X行给了我一个错误,说:无法将Regexp转换为Integer

    1 回复  |  直到 13 年前
        1
  •  1
  •   Neil Slater    13 年前

    如果我模拟你问题中的数据结构,我会得到:

    @l2_mastertest = { '3.1.4' => 7, '1.2.3' => 8 }
     => {"3.1.4"=>7, "1.2.3"=>8}
    
    @l2_mastertest.each_with_index { |row2,index| p row2,index }
    ["3.1.4", 7]
    0
    ["1.2.3", 8]
    1
    

    所以像这样的结构 row2[0][ /(\d+\.\d+)/ ] 与例如相同。 "3.1.4"[ /(\d+\.\d+)/ ]

    编辑:删除了我以前的“答案”,因为实际上 "3.1.4"[ /(\d+\.\d+)/ ] => "3.1" ,这在Ruby中很好(我今天学到了一些东西:-)。其他一些东西(可能在未显示的代码中)使@l2_mastertest散列的行为与预期不符。

    这可能是一个数据库/模型问题,正如评论人士所建议的那样, row[0] 不包含字符串。

    相反,我建议 SELECT * FROM builds; 这是有风险的,因为您依赖于数据库以特定的顺序返回列。您应该更改它以获取所需的列数据,例如。

    SELECT version, result, build_id FROM builds;
    

    这样您就可以确定以后的处理是针对您认为的列进行的。简单地重新构建或传输数据库可能会改变RDBMS在 SELECT * 并使先前工作的代码中断。