Robert Klemme
11/25/2004 9:57:00 AM
"Anders Engström" <aengstrom@gnejs.net> schrieb im Newsbeitrag
news:20041125084737.GA25462@metamorph.gnejs.net...
> On Thu, Nov 25, 2004 at 05:27:58PM +0900, Robert Klemme wrote:
> >
> > "Anders Engström" <aengstrom@gnejs.net> schrieb im Newsbeitrag
> > news:20041125073108.GA25131@metamorph.gnejs.net...
> > > On Thu, Nov 25, 2004 at 04:18:04PM +0900, itsme213 wrote:
> > > > I have some closure context captured in a proc, and want to create
a
> > method
> > > > on a class from that. What is a good way to do this?
> > > >
> > >
> > > Something like the following should work:
> > >
> > > class Test
> > > # The class to add the method to.
> > > end
> > >
> > > # The proc we want to turn into a method
> > > block = proc {|arg|
> > > puts "Proc got #{arg}"
> > > }
> > >
> > > # Define the method
> > > Test.__send__(:define_method, :run_proc, &block)
> >
> > Alternatively:
> >
> > Test.instance_eval { define_method(:run_proc, &block) }
> >
> > > # Make it public
> > > Test.__send__(:public, :run_proc)
> >
> > I think that's not necessary as methods are public by default.
> >
>
> I didn't think that either... but when I ran the code without the
> 'publification call' I got:
>
> proc_to_meth.rb:13: private method `run_proc' called for
> #<Test:0x40120ca0> (NoMethodError)
>
> This is on
>
> Linux metamorph 2.6.6 #1 Mon May 31 12:59:53 CEST 2004 i686 GNU/Linux
> ruby 1.8.2 (2004-11-03) [i386-linux]
Hm, strange:
10:53:58 [robert.klemme]: irbs
>> class Foo
>> end
=> nil
>> Foo.send(:define_method, :bar) { "bar" }
=> #<Proc:0x10186cd0@(irb):3>
>> Foo.new.bar
=> "bar"
>> class Bar
>> private
>> end
=> Bar
>> Bar.send(:define_method, :bar) { "bar" }
=> #<Proc:0x10165538@(irb):10>
>> Bar.new.bar
=> "bar"
>> RUBY_VERSION
=> "1.8.1"
>> system *%w{uname -a}
CYGWIN_NT-5.0 bond 1.5.11(0.116/4/2) 2004-09-04 23:17 i686 unknown unknown
Cygwin
=> true
>>
Maybe that behavior changed between 1.8.1 and 1.8.2. Matz?
Cheers
robert