--- On Fri, 11/21/08, Jim Freeze <jimfreeze@...> wrote:
> From: Jim Freeze <jimfreeze@...>
> Subject: Re: [arctan] Double Meta
> To: arctan@yahoogroups.com
> Cc: austin-rb@googlegroups.com
> Date: Friday, November 21, 2008, 8:05 AM
> On Thu, Nov 20, 2008 at 4:37 PM, Eric Mahurin
> <eric_mahurin@...> wrote:
> > Wondering the same thing myself. Jim, do you have an
> application?
>
> Not really. I was really just exploring the language.
> Besides, this
> type of things already
> exists with #dup and #clone. I suppose if you wanted to add
> methods to
> an object that
> were stripped away even with a #clone, this would be the
> way to do it.
>
> > Sorry I didn't make it. I wanted to come, but
> something came up.
> > While on the topic of singletons, this is how I make
> my singleton *objects*:
> >
> > singletonObject = Class.new(base_class) { # base_class
> defaults to Object
> > def foo ... # or define_method
> > ...
> > }.new
> >
> > All this does is create an anonymous class and call
> new on the class to
> > create the singleton object (for that class). I find
> this more intuitive and
> > readable than dealing with meta classes.
>
> And once you have that object, what are it's uses?
http://en.wikipedia.org/wiki/Singleton_pattern
I'm not sure my instance of an anonymous class actually matches the "singleton
pattern", but I believe it is useful in the same scenarios.
Here are a few ways I've used this:
- As empty/null node in a data structure. I believe I used this in the rope
quiz.
- To create "Min"/"Max" objects which are always greater/less than whatever they
are compared to. The anonymous class for these just defines the "<=>" method.
- To make an on-the-fly duck which mimics the interface of something else
sufficiently to be used in a method/class/etc using simple duck-typing. An
example I've used in the past is for a method that takes an object that responds
to #===. I wanted to use a Set for matching, but it didn't use #=== for
matching, but #include? instead. Solution: define an object on the fly from an
anonymous class that does a define_method for #=== which references the Set
object (using #include?).
You could also think of the True, False, and Nil objects very similar to these
except they come from a named class instead of an anonymous class.
Eric