B
Ben
I'm a C++ programmer learning Ruby. I would like to make a class that
extracts patterns from a file, and returns an array of values. I
have:
class Extracter
def initialize(pattern, location)
@pattern =3D pattern
@loc =3D location
end
def extract(stream)
pats =3D Array.new
stream.each_line do |line|
if line =3D~ @pattern then
pats << $~[@loc]
end
end
pats
end
end
cppFile =3D File.new("foo.cpp")
incEx =3D Extracter.new(/#include\s*[<"](.*)[>"]/, 1)
includesArr =3D incEx.extract(ccpFile)
So far, so good. If not, let me know what I've done wrong. Next, I
want to extend the Extracter class to hold an array of patterns and
locations, or a Proc parser that will return the interesting value
(this is for lines that are tougher than regexp). How do I create a
constructor that will take different types and create the appropriate
arrays internally? The options I see are:
1) Call .class.to_s on each parameter to match the type:
"pattern.class.to_s =3D~ /Array/ then # I have an array of regexp
2) Use a non-trvial data structure to map symbols to types
3) Use different functions to fill out my extracter:
def add_array
def add_parser
What am I missing? Am I doing this entirely wrong for Ruby?
-Ben
extracts patterns from a file, and returns an array of values. I
have:
class Extracter
def initialize(pattern, location)
@pattern =3D pattern
@loc =3D location
end
def extract(stream)
pats =3D Array.new
stream.each_line do |line|
if line =3D~ @pattern then
pats << $~[@loc]
end
end
pats
end
end
cppFile =3D File.new("foo.cpp")
incEx =3D Extracter.new(/#include\s*[<"](.*)[>"]/, 1)
includesArr =3D incEx.extract(ccpFile)
So far, so good. If not, let me know what I've done wrong. Next, I
want to extend the Extracter class to hold an array of patterns and
locations, or a Proc parser that will return the interesting value
(this is for lines that are tougher than regexp). How do I create a
constructor that will take different types and create the appropriate
arrays internally? The options I see are:
1) Call .class.to_s on each parameter to match the type:
"pattern.class.to_s =3D~ /Array/ then # I have an array of regexp
2) Use a non-trvial data structure to map symbols to types
3) Use different functions to fill out my extracter:
def add_array
def add_parser
What am I missing? Am I doing this entirely wrong for Ruby?
-Ben