Gerardo Santana Gómez Garrido
12/29/2005 6:08:00 AM
2005/12/28, Eero Saynatkari <ruby-ml@magical-cat.org>:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> (Sorry if this is a duplicate.)
>
> On 2005.12.29 14:04, Gerardo Santana Gómez Garrido
> <gerardo.santana@gmail.com> wrote:
> > 2005/12/28, Max Eskin <kurtkilgor@yahoo.com>:
> > > Hi,
> > > I am just starting to use Ruby. I'm wondering, once a class has been
> > > declared, is there any way to lock it to prevent further methods from
> > > being defined? In other words is there a way to make Ruby act like a
> > > static language for some classes?
> >
> > Use Module#freeze
> >
> > class A
> > def self.f(a)
> > a + 1
> > end
> > end
> >
> > puts A.f(1) # => 2
> >
> > A.freeze
> >
> > #=> runtime error: "can't modify frozen object (TypeError)"
> > class A
> > def self.f(a)
> > a - 1
> > end
> > end
> >
> > puts A.f(1)
>
> One can still A.dup, but I think this is a reasonable way :)
The original poster was concerned about adding methods. In such case
#dup is inoffensive.
--
Gerardo Santana