What is the best way to separate a code chunk (string) into its “main parts” and its “expected return parts”? Here are my definitions:
- An expected return part is a line that matches
/^[ \t]*#[ \t]*=>/followed by zero or more consecutive lines that do not match/^[ \t]*#[ \t]*=>/but match/[ \t]*#(?!\{)/. - A main part is any consecutive lines that is not an expected return part.
Main parts and expected return parts may appear multiple times in a code chunk.
Given a string of code chunk, I want to get an array of arrays, each of which includes a flag of whether it is an expected return part, and the string. What is the best way to do this? For example, given a string code whose content is:
def foo bar
"hello" if bar
end
#=> foo(true) == "hello"
#=> foo(false) == nil
a = (0..3).to_a
#=> a == [
# 0,
# 1,
# 2,
# 3
# ]
I would like a return that would be equivalent to this:
[[false, <<CHUNK1], [true <<CHUNK2], [true, <<CHUNK3], [false, <<CHUNK4], [true, <<CHUNK5]]
def foo bar
"hello" if bar
end
CHUNK1
#=> foo(true) == "hello"
CHUNK2
#=> foo(false) == nil
CHUNK3
a = (0..3).to_a
CHUNK4
#=> a == [
# 0,
# 1,
# 2,
# 3
# ]
CHUNK5
This regex should match all expected returns:
Extract and then replace all expected returns from your string with a separator. Then split your string by the separator and you will have all main parts.
Test it here: http://rubular.com/r/ZYjqPQND28
There is a slight problem with your definition pertaining to the regex
/[ \t]*#(?!>\{)/, by which I am assuming you meant/[ \t]*#(?!=>)/, because otherwisewould count as one chunk
Another approach would be to use this regex (completely unoptimised):
to simply split it into chunks correctly, then do a relatively simple regex test on each chunk to see if it is an expected return or main part.