2016-09-28 39 views
0

我有许多的日志文件,每个文件包含像这样的一行:红宝石检查是否字符串包含子

THIS LINE IS DIFFERENT CASE_WINDOWS_TEST_00 PASSED 

我在寻找,如果行包含“_XXX_TEST_”字符串。我创建的哈希:

@@groups = { 
    "_LINUX_TEST_" => "Linux_tests", 
    "_WINDOWS_TEST_" => "Windows_tests" 
} 

要检查行包含(从@@基团的键)的子我实现它返回从@@基团的值的方法get_group_name。

def get_group_name(searchLine) 
    @@groups.keys.each do |i| 
     if searchLine.include? i 
      return @@groups[i] 
     end 
    end 
end 

它工作正常,返回适当的值。我在另一个遍历整个日志文件的方法中使用这个方法。

def get_group_name_from_file(fileName) 
    # fileName - filename or path to the file.txt 
    file = File.open(fileName) 
    while (line = file.gets) 
     found = get_group_name(line) 
     if found 
      return found 
     end 
    end 
end 

这就是问题所在。方法get_group_name_from_file返回来自@@组哈希的密钥列表,而不是一个字符串(来自该哈希的值)。

+0

无法重现 –

回答

1

我想,可能出现这个问题时,你的日志文件不具有行,以包含您的任何@@ groups.keys的,所以解决这个问题,你可以添加此行:

@@groups = { 
    "_LINUX_TEST_" => "Linux_tests", 
    "_WINDOWS_TEST_" => "Windows_tests" 
    } 

    def get_group_name(searchLine) 
    @@groups[@@groups.keys.find { |key| searchLine.include? key }] 
    end 

    def get_group_name_from_file(fileName) 
    # fileName - filename or path to the file.txt 
    file = File.open(fileName) 
    while (line = file.gets) 
     found = get_group_name(line) 
     return found if found 
    end 
    end 
+0

你的猜测是正确的,我想,但它应该是固定的另一种方法。 –

+0

@SergioTulentsev是你的权利! –

+0

不错,但没有。此代码是超级破碎:) –

1

它发生的时候,它返回由每个方法返回,如果控制不达到高达输出:

return @group[i]; 

您可以更新方法:

def get_group_name(searchLine) 
    @@groups.keys.each do |i| 
    if searchLine.include? i 
     return @@groups[i] 
    end 
    end 
    return nil 
end 

还有一个选项:

def get_group_name(searchLine) 
    @groups.keys.detect do |i| 
    if searchLine.include? i 
     return @groups[i] 
    end 
    end 
end 
+0

多一个选项: def get_group_name(searchLine) @ groups.keys.detect do | i | 如果searchLine.include?我 返回@groups [i] 结束 结束 结束 – Anuja

+0

如果我们使用检测,我们不需要'如果'或'返回' –

+0

我们需要它,因为迭代是关键而不是价值。所以它会返回关键但我们需要价值。 – Anuja

相关问题