"Hal E. Fulton" <hal9000 / hypermetrics.com> wrote:
> ----- Original Message -----
> From: Brian Fundakowski Feldman <green / FreeBSD.org>
> To: ruby-talk ML <ruby-talk / ruby-lang.org>
> Sent: Friday, August 24, 2001 10:07 AM
> Subject: [ruby-talk:20291] new toy: method_var
> 
> 
> > After seeing a million examples of overriding methods in classes by
> aliasing
> > an existing method to something with a more obscure name, defining over
> that
> > method and then calling the alias of the old method in the new method's
> > code, I convinced myself there HAD to be a better way.  In that vein, I've
> > implemented the ability to "attach" an anonymous variable to a given
> method.
> >
> > It works like this:
> >
> 
> [snip]
> 
> That's interesting... but it isn't quite fitting
> into my brain right now. That's not a criticism,
> just a statement of my slowness today...
> 
> Two questions:
> 
> 1. Can you show another example? Say, one
> that replaces <=> for String by removing all
> spaces/punctuation, doing an upcase, and
> then calling the old compare?

Okay, I'll try.

module MyStringComparison
    def self.enabled
        String.class_eval <<-'END'
            old = instance_method(:<=>)
            def <=>(other)
                c1, c2 = [self, other].collect {|s|
                    s.gsub(/[^[:alnum:]]*/, '').upcase
                }
                method_var.bind(c1).call(c2)
            end
            define_method_var(:<=>, old)
        END
        begin
            yield
        ensure
            String.class_eval <<-'END'
                define_method(:<=>, method_var(:<=>))
            END
        end
    end
end

irb(main):003:0> "Abc...?" <=> "A B C!"
1
irb(main):004:0> MyStringComparison::enabled {"Abc...?" <=> "A B C!"}
0
irb(main):005:0> "Abc...?" <=> "A B C!"
1

> 2. Is it possible somehow to combine the
> instance_method and define_method_var
> steps? That would be neat if so, I think...

Not very easily :-/

-- 
 Brian Fundakowski Feldman           \  FreeBSD: The Power to Serve!  /
 green / FreeBSD.org                    `------------------------------'