Regular expression for get block by block

if i have a file like this:

class My Class < Core::TEstsaldjl

def test01dfldsfl
assert(“djdjdj”)
puts “logiicl”
end
def test02sldkfjdsjl
assert(kdjslafdljs)
end

def test03
mymethod

#this is just an example

end
def setup
super()
end
end

and i want to get the code inside the test methods as an array like this
first position:
assert(“djdjdj”)
puts “logiicl”
second position:
assert(kdjslafdljs)
third position:
mymethod

#this is just an example

what kind of regular expression i can use. I was trying some like this:
/(^\sdef test[^def]+^\send\s*)/m

but ^def will treat it as single characters not as a word…

any idea?

Mario R. wrote in post #1156915:

what kind of regular expression i can use. I was trying some like this:
/(^\sdef test[^def]+^\send\s*)/m

but ^def will treat it as single characters not as a word…

any idea?

This one make the job,
s.scan(/\bdef\b(.*?)\bend\b/m)

but only if your methods codes does not contain a ‘end’ !

for a general case, you need a real parser.
ruby_parser and ruby2ruby should do the job.
see GitHub - seattlerb/ruby2ruby

yep that’s the case… I can have ‘ends’ and other stuff in there

Mario R. wrote in post #1157108:

yep that’s the case… I can have ‘ends’ and other stuff in there

=====================================
require ‘sexp’
require ‘ruby_parser’
require ‘ruby2ruby’

code=<<EEND
def aa(a)
a*2
end
def bb(a,b)
while a>b
a
end
end
EEND

def find_defn(sexp,l)
node,*tail=sexp
case node
when :block
tail.each { |a| find_defn(a,l) }
when :defn
l << {name: tail.first, code: Ruby2Ruby.new.process(tail.last)}
end
l
end

tree=RubyParser.new.process( code || File.read(ARGV.first) )

find_defn(tree,[]).each do |node|
puts
“======================\nname=#{node[:name]}\ncode=<<<\n#{node[:code]}\n>>>\n”
end

give:

ruby r3r.rb
======================
name=aa
code=<<<
(a * 2)

======================
name=bb
code=<<<
while (a > b) do
a
end