Ruby 查找所有常量

标签 ruby

如果这是一个简单的问题,我是 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/

相关文章:

ruby-on-rails - 无法安装 gem - 无法构建 gem native 扩展 - 无法加载此类文件 -- mkmf (LoadError)

ruby 年哈希生成

ruby - 为什么 Google 的 Cityhash gem 安装不了?

ruby-on-rails - 如何在 Rails 2.3.14 应用程序中配置 memprof?

ruby-on-rails - 如何在 savon 2.0.2 中使用证书

ios - 如何完全删除 calabash-ios/robotframework

ruby - 如何计算在 Ruby 中创建的对象数

ruby-on-rails - 部署 Rails - 在任何源中都找不到 rake-11.1.2

ruby-on-rails - #<PG::Result:0x007fcc82900a78> 的未定义方法 `empty?'

ruby-on-rails - 通过子属性 Ruby on Rails 选择和排序父记录