Overloading

I don't quite understand your original problem (wouldn't the the
ProcExtractor and the PatternLocationExtractor be two different
things?), but in answer to your question, you can check the type of the
thing with a case statement like so:

  case thing
    when Array : @arrays << thing
    when Proc : @procs << thing
    else
      raise "Crazy monkey, you gave me a #{thing.class}"
  end

or, equivalently:

  if Array === thing
  @arrays << thing
  elsif Proc === thing
  @procs << thing
  else
      raise "Crazy monkey, you gave me a #{thing.class}"
  end

···

-----Original Message-----
From: Ben [mailto:benbelly@gmail.com]
Sent: Monday, 26 September 2005 11:38 AM
To: ruby-talk ML
Subject: Overloading

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 = pattern
    @loc = location
  end
  def extract(stream)
    pats = Array.new
    stream.each_line do |line|
      if line =~ @pattern then
        pats << $~[@loc]
      end
    end
    pats
  end
end

cppFile = File.new("foo.cpp")
incEx = Extracter.new(/#include\s*[<"](.*)[>"]/, 1) includesArr =
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 =~ /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

#####################################################################################
This email has been scanned by MailMarshal, an email content filter.
#####################################################################################

Well, maybe. I would like to pass through the files just once - there
are likely to be several hundred files, and they will sometimes be
quite long. I was hoping to use Ruby's ability to store multiple
types to do that. Hmm. Maybe . . .
I'll make a pattern / location parser, and the extracter will just
hold parsers. That makes more sense. Thanks.
It always helps to talk things out, eh? :slight_smile:

-Ben

···

On 9/25/05, Daniel Sheppard <daniels@pronto.com.au> wrote:

I don't quite understand your original problem (wouldn't the the
ProcExtractor and the PatternLocationExtractor be two different
things?),