恐怕正则表达式不会带你走太远。例如,考虑以下表达式(它们也是有效的 Ruby)
"(foo.bar.size.split( '.' )).last"
"(foo.bar.size.split '.').last"
"(foo.bar.size.split '( . ) . .(). .').last"
问题是,调用列表实际上是调用树。最简单的解决方案可能是使用 Ruby 解析器并根据您的需要转换解析树(在此示例中,我们递归地下降到调用树,将调用收集到一个列表中):
# gem install ruby_parser
# gem install awesome_print
require 'ruby_parser'
require 'ap'
def calls_as_list code
tree = RubyParser.new.parse(code)
t = tree
calls = []
while t
# gather arguments if present
args = nil
if t[3][0] == :arglist
args = t[3][1..-1].to_a
end
# append all information to our list
calls << [t[2].to_s, args]
# descend to next call
t = t[1]
end
calls.reverse
end
p calls_as_list "foo.bar.size.split('.').last"
#=> [["foo", []], ["bar", []], ["size", []], ["split", [[:str, "."]]], ["last", []]]
p calls_as_list "puts 3, 4"
#=> [["puts", [[:lit, 3], [:lit, 4]]]]
并显示任何输入的解析树:
ap RubyParser.new.parse("puts 3, 4")