lundi 23 mars 2020

Convert bunch of string to array and compare two arrays to get common values in both

This is my code -

 def self.constant_discovery(file_name, pattern) 
  matches = File.open(file_name).read.scan(pattern).uniq.flatten.compact
  matches_found = matches.map {|key| key.split(',')[0].scan(/^[A-Z]+(?:_[A-Z]+)*$/)}.flatten
  search_pattern = /([A-Z]+_)*[A-Z]+ = '.+'/
  File.open(file_name) do |f|
   lines = f.find_all {|line| line =~ search_pattern }
   lines.each do |line|
     if line.include?('=')
       print line unless line.empty?
       required_output = matches_found & line
     end 
    line
   end
 end
  matches 
end

By the above code I'm getting matches_found values like below, ["TEST_ONE", "TEST_TWO", "TEST_THREE","TEST_FOUR"]

Where as, line is producing output like this,

TEST_ONE = 'testone'
TEST_TWO = 'testtwo'
TEST_THREE = 'testthree'
TEST_FOUR = 'testfour'
KEY_AS_PRIMARY = 'primary'

In the require_output I need to get the common constant values from matches_found and line and from that common constant value I have to return the value which the common constant assigned to. While trying this I'm facing issue when comparing matches_found and line and getting error like "failed with error no implicit conversion of String into Array "

By this I understood that I have to convert values of line to an array and then should compare it with matches_found, after this I'll be getting common constant from both the arrays in required_output and later I can get the value which is assigned to those common constants as return values of that method. As I'm very new to ruby can someone please help me with it?

Aucun commentaire:

Enregistrer un commentaire