2008-11-09 49 views
1

searchterms.rb流量没有终止循环和打印多余的字符

search = "1|butter+salted|Butter salt|Butter|Túrós csusza|Margarine|Potato 
      2|butter+whipped|Shea butter|Butter|Pastry bag|Cream bun|Butter cream 
      3|butter+oil+anhydrous|Ultralight backpacking|Odell\'s|Ghee|Fragrance extraction|Perfume 
      4|cheese+blue|Blue cheese|Shropshire Blue cheese|Buxton Blue cheese|Danish Blue cheese|Blue cheese dressing 
      5|cheese+brick|Brick cheese|Oaxaca cheese|List of American cheeses|Herve cheese|Trappista cheese 

. 
. 
. 

search = search.split('\n') 
catalog = String.new 
a = 0; until a == search.length 

    line = search[a].split('|') 
    id = line.first 
    term = line[1] 

    puts id + "|" + term 
    puts "  1 #{line[2].nil? ? '' : line[2]}" 
    puts "  2 #{line[3].nil? ? '' : line[3]}" 
    puts "  3 #{line[4].nil? ? '' : line[4]}" 
    puts "  4 #{line[5].nil? ? '' : line[5]}" 
    puts "  5 #{line[6].nil? ? '' : line[6]}" 

    choice = gets 
    choice = choice.chomp.to_i 

    catalog = "#{id}|#{term}|#{line[choice]}\n" 

    %x[echo "#{catalog}" >> updated_terms] 

    a += 1 
end 

$ ruby searchterms.rb 
1|butter+salted 
     1 Butter salt 
     2 Butter 
     3 Túrós csusza 
     4 Margarine 
     5 Potato 
2 # I don't know why this figure is printed. 
2 
$ 

我如何得到这个工作?我必须为每个食物选择最相关的术语。

我也得上设置任何其他号码,即可开始奇怪的错误:

searchterms.rb:7525:  
     line = search[a].split('|') 
    private method `split' called for nil:NilClass (NoMethodError) 
+0

您也正在为您的循环使用非标准成语 - 考虑使用`(0 ... search.length).each do | a |`或`0.upto(search.length - 1)do | a |`并删除你的'a + = 1`行。 – rampion 2008-11-09 22:14:52

回答

2

您需要使用

search.split("\n") 

,而不是

search.split('\n') 

单引号防止它被解释为实际的换行符。这就是为什么循环终止的原因 - 数组的长度根本不被分割,为1.在第一次迭代结束时,一个(它是0)变为+ = 1,这是非分裂阵列。

+0

如此简单,我很高兴。这解决了这两个问题,我的朋友:-) – Jesse 2008-11-09 15:44:46