1

I'm analyzing some code and I'm looking for string literals, to check if I have any duplicates. For example, if I have

def test_foo
  input_filename = "foo.txt"
  # ...
end

def test_bar
  input_filename = "bar.txt" # Fine
  # ...
end

def test_baz
  # Bad! Refactor it to a constant that's shared by test_foo and test_baz
  input_filename = "foo.txt" 
  # ...
end

I want the analysis program to tell me that ["foo.txt", "bar.txt", "foo.txt"] exist in my source code.

How can I do this?

1
  • 1
    Don't forget the %q and %Q versions... Commented Dec 8, 2011 at 23:47

1 Answer 1

5

If you install ruby_parser or parsetree, you'll be able to do something like this (assuming that the program text is in text):

result = RubyParser.new.parse(text)
result.flatten.to_a.select {|elt| elt.is_a?(String)}

(This could obviously be nicer, but it should be enough to get you started!)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! PS: result.flatten.grep(String) is one way to code golf it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.