Ruby if语句用于排除多个字符串变体

时间:2016-01-21 19:15:49

标签: ruby

我正在尝试解析我创建的数组,最终将'good'值写入文件。数组可能看起来像这样,但内容可能会改变,所以我无法匹配某个值:

function agregar_fporder(fporder)
    {
        console.log('agregar_fporder() ejecutado');
        console.log("fporder: "+fporder);
        var tr = '';
        tr += '<tr class="item fporder">';
        tr +=       '<td class="nro_orden"></td>';
        tr +=       '<td class="id">'+fporder.FpordersProduct.product_id+'</td>';
        tr +=       '<td class="code">'+fporder.FpordersProduct.product_code+'</td>';
        tr +=       '<td class="name">'+fporder.FpordersProduct.product_name+'</td>';
        tr +=       '<td></td>';
        tr +=       '<td></td>';
        tr +=       '<td></td>';
        tr +=       '<td></td>';
        tr +=       '<td></td>';
        tr +=       '<td class="nro_pedido">';
        tr +=       '</td>';
        tr +=       '<td class="quantity">';
        tr +=       '</td>';
        tr +=       '<td class="um_id">';
        tr +=       '</td>';
        tr +=       '<td></td>';
        tr +=       '<td>';
        tr +=       '</td>';
        tr +=       '<td></td>';
        tr +=       '<td></td>';
        tr += '</tr>';

        var item = $('table#items tr.items.fporder').find('td.code input.code[value="'+fporder.FpordersProduct.product_code+'"');
        console.log('item: '+item);
    }

我认为在写入文件之前检查数组值并且不写我知道我不想要的值是有意义的。在这种情况下,值始终为:

array = ["10.10.10.0/24", "10.10.10.1/32", "10.10.10.129/32", "127.0.0.0/8", "169.254.0.0/16", "192.168.1.0/24", "255.255.255.255/32"] 

我的初始 10.10.10.1/32 10.10.10.129/32 127.0.0.0/8 169.254.0.0/16 255.255.255.255/32 语句看起来像这样,有点完成了我的目标,但并非完全:

if

导致结果(不应包括第2行和第3行):

 if !network.include?("/32" || "127.0.0.0/8" || "169.254.0.0/16" || "255.255.255.255/32")
   file.write("#{network}\n")
 end

我做错了什么?有没有更好的方法来执行查找/匹配/排除?

2 个答案:

答案 0 :(得分:1)

您无法使用&#34;或&#34; ||就是这样。

更好的可能是......

exclude_entries = [ '/32', 
                    '127.0.0.0/8',
                    '169.254.0.0/16',
                    '255.255.255.255/32'
                  ]
match_pattern = Regex.new(exclude_entries.join('|'))

(array.reject{|n| n =~ match_pattern}.each do |network|
     file.write("#{network}\n")
end

问题是表达式"/32" || "127.0.0.0/8" 总是返回&#34; / 32&#34; ......&#34;或&#34;只返回第一个&#34; truthy&#34;价值和&#34; / 32&#34;是&#34; truthy&#34;

编辑使用正则表达式以排除部分文本。

答案 1 :(得分:1)

networks = ["10.10.10.0/24", "10.10.10.1/32", "10.10.10.129/32", "127.0.0.0/8", "169.254.0.0/16", "192.168.1.0/24", "255.255.255.255/32"] 
banned_networks = [/\/32/, "127.0.0.0/8", "169.254.0.0/16", "255.255.255.255/32"]

networks.reject do |e|
  case e
  when *banned_networks
    true
  end
end.each {|network| file.write("#{network}\n")}