3

I am new to Ruby so sorry if it's a simple question. I want to open a ruby file and search all constants, but I don't know the right regular expression.

Here is my simplified code:

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 
8
  • 1
    To do it reliably you need to parse the code into AST, and this is not something you can do with regexes. Commented Dec 5, 2012 at 10:43
  • so i cant parse for all expression written in caps? Commented Dec 5, 2012 at 10:46
  • does your file simply contain a known set of classes/modules ? Commented Dec 5, 2012 at 10:49
  • i want to parse several files, just to know which constants, functions ect they contain. Commented Dec 5, 2012 at 10:52
  • 2
    @user1878703: you get all words that are in caps, but what about this one MAGIC_STRING = "This is a word in CAPS"? How many constants do you see here? Commented Dec 5, 2012 at 10:55

2 Answers 2

2

You can use Ripper library to extract the tokens.

For example, this code will return you constants and methods names for the file

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"] 
Sign up to request clarification or add additional context in comments.

Comments

0

As Sergio Says searching for words with Caps won't just give you constants but if it's good enough it's good enough.

The regexpression you are looking for is something like

if (line =~ /[^a-z][A-Z]/) 

Which says match any capital that is not preceded by a lower case letter. Of course this will only count one per line so you might like to consider tokenising the stream and working on tokens, not lines.

3 Comments

this isnt working for me it still find words like Controller, i have to use ruby 1.8.7 if its important.
Controller is a constant (assuming that it is a variable identifier, of course), since it starts with a capital letter.
the word was maybe not the best example but it outputs me all words which start with a capital, i want only words like THIS or EXAMPLE

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.