Reputation: 139
I have many log files, each contains a line like this one:
THIS LINE IS DIFFERENT CASE_WINDOWS_TEST_00 PASSED
I'm searching if line contains "_XXX_TEST_" string. I created a hash:
@@groups = {
"_LINUX_TEST_" => "Linux_tests",
"_WINDOWS_TEST_" => "Windows_tests"
}
To check if the line contains a substring (a key from @@groups) I implemented method get_group_name which returns a value from @@groups.
def get_group_name(searchLine)
@@groups.keys.each do |i|
if searchLine.include? i
return @@groups[i]
end
end
end
It works fine, returns proper values. I use this method in another method that iterates through log file.
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
And here is the problem. Method get_group_name_from_file returns list of keys from @@groups hash instead of one string (a value from that hash).
Upvotes: 0
Views: 2860
Reputation: 4440
I think, this problem could appear when your log file doesn't have lines that include any of your @@groups.keys, so for solve this problem, you can add this lines:
@@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
Upvotes: 1
Reputation: 654
It happens when it returns the output returned by each method if control doesn't reach upto:
return @group[i];
You can update method as:
def get_group_name(searchLine)
@@groups.keys.each do |i|
if searchLine.include? i
return @@groups[i]
end
end
return nil
end
One more option:
def get_group_name(searchLine)
@groups.keys.detect do |i|
if searchLine.include? i
return @groups[i]
end
end
end
Upvotes: 1