如果这是一个简单的问题,我是 Ruby 的新手,很抱歉。 我想打开一个 ruby 文件并搜索所有常量,但我不知道正确的正则表达式。
这是我的简化代码:
def findconst()
filename = @path_main
k= {}
akonstanten = []
k[:konstanten] = akonstanten
if (File.exists?(filename))
file = open(filename, "r")
while (line = file.gets)
if (line =~ ????)
k[:konstanten] << line
end
end
end
end
最佳答案
您可以使用 Ripper提取 token 的库。
例如,此代码将返回文件的常量和方法名称
A = "String" # Comment
B = <<-STR
Yet Another String
STR
class C
class D
def method_1
end
def method_2
end
end
end
require "ripper"
tokens = Ripper.lex(File.read("file.rb"))
pp tokens.group_by { |x| x[1] }[:on_ident].map(&:last)
pp tokens.group_by { |x| x[1] }[:on_const].map(&:last)
# => ["method_1", "method_2"]
# => ["A", "B", "C", "D"]
关于Ruby 查找所有常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13721350/