arrays - 将一堆字符串转换为数组并比较两个数组以获得两者的共同值
问题描述
这是我的代码 -
在这里,我试图通过使用正则表达式搜索所有文件来获取所有附加了 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_found和line之间的公共常量值,从这些公共常量中只返回那些在某处声明并分配了值的常量。可以在克隆的 repo 中的任何位置声明常量的值。
当我尝试这样做时,我在比较matches_found和错误消息时遇到了问题“失败并没有将字符串隐式转换为数组”
通过这个我明白我必须将行的值转换为数组。然后应该将它与matches_found进行比较,在此之后我将从required_output中的两个数组中获取公共常量。后来我可以得到那些已经分配给那些公共常量的值。最后,该方法应该产生以下返回值,
[testone,testtwo,testthree,testfour]
由于我对红宝石很陌生,有人可以帮我吗?很抱歉粘贴了我的整个方法。请帮我解决这个问题。
解决方案
推荐阅读
- laravel - 如何使用 Socialite 和 Google 设置 Homestead 的重定向 URL?
- javascript - AJAX 代码以“Get #ADRESS# 404”结尾
- java - 如何修复 kafka-start-server.sh 上的“java.lang.UnsupportedClassVersionError”
- wordpress - 更新 wp_posts 的 ID 和 wp_postmeta 的 post_id 会导致网页内容丢失,为什么?
- keycloak - 如何在 keycloak 版本之上管理自定义的 keycloak SPI、实体、Rest 端点?
- hadoop - 将 oozie 工作流程从一个用户转移到另一个用户的最佳方式是什么?
- automated-tests - 我可以使用 Testcafe 执行 Rendr App 功能吗?
- programming-languages - 类、包、命名空间和模块之间有什么区别?
- envoyproxy - 如何在 envoy 中创建自定义分片逻辑?
- linux - 超过一定大小(~1450)的 TCP 消息被“卡住”