首页 > 解决方案 > 将一堆字符串转换为数组并比较两个数组以获得两者的共同值

问题描述

这是我的代码 -
在这里,我试图通过使用正则表达式搜索所有文件来获取所有附加了 feature_toggle 字符串的常量,该正则表达式已从 git 克隆并存储在本地,例如,

feature_enabled?(TEST_ONE) 
feature_enabled?(TEST_TWO)
feature_enabled?(TEST_THREE)
feature_enabled?(TEST_FOUR)
feature_enabled?(KEY_AS_PRIMARY)

由此我将在matches_found中获得以下值

 ["TEST_ONE", "TEST_TWO", "TEST_THREE","TEST_FOUR","KEY_AS_PRIMARY"]

这是我试图实现的方法。

    # public: retrieve the constant feature names based on the asset passed
    #
    # filename - path of each file under a repository for running the scan for example - /Users/sagarPC/Desktop/project/tmp/icdev/somefolder/app/models/project_one/orion/add_me_task.rb
    # pattern - regex pattern which search for the names.Ex- /(?:\.|!)?feature_enabled\?\((.*?)\)/m
    #
    # Ex - feature_enabled?(TEST_ONE)
    #
    # returns each constant's value in an array
    # Ex - [testone,testtwo,testthree,testfour]

    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

通过上面的代码,我得到了如下所示的matches_found值,

["TEST_ONE", "TEST_TWO", "TEST_THREE","TEST_FOUR","KEY_AS_PRIMARY"]

其中,生产线正在产生这样的输出,

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

这些常量可以在克隆存储库的某个地方声明,也可以在其他地方使用。在require_output中,我需要获取matches_foundline之间的公共常量值,从这些公共常量中只返回那些在某处声明并分配了值的常量。可以在克隆的 repo 中的任何位置声明常量的值。

当我尝试这样做时,我在比较matches_found和错误消息时遇到了问题“失败并没有将字符串隐式转换为数组

通过这个我明白我必须将的值转换为数组。然后应该将它与matches_found进行比较,在此之后我将从required_output中的两个数组中获取公共常量。后来我可以得到那些已经分配给那些公共常量的值。最后,该方法应该产生以下返回值,

[testone,testtwo,testthree,testfour]

由于我对红宝石很陌生,有人可以帮我吗?很抱歉粘贴了我的整个方法。请帮我解决这个问题。

标签: arraysrubyruby-on-rails-3ruby-on-rails-5

解决方案


推荐阅读