module_eval: adding a method to a class with a proc 
Author Message
 module_eval: adding a method to a class with a proc

i'm having a little problem that i'm not sure how to solve. i'm trying
to add a method to a class with a Proc using module_eval:

a rough example:

  x = Proc.new { 5 + 5 }

  class C
    def initialize
    end
  end

  C.module_eval {
    def ten
      x
    end
  }

  c = C.new
  puts c.ten

i end up getting 'ten': undefined local variable or method. that makes
sense but how do i get around it? what i want is for the definition of
ten to evalutate like:

  def ten
    5 + 5
  end

anyone?

~transami

  _(")_  letter man
   \v/  
   ^ ^



Fri, 07 Jan 2005 02:20:49 GMT  
 module_eval: adding a method to a class with a proc

Quote:
>   x = Proc.new { 5 + 5 }

>   class C
>     def initialize
>     end
>   end

>   C.module_eval {
>     def ten
>       x
>     end
>   }

You've got a scoping problem, and x isn't visible inside "def ten".
This works (I think), but I'm not sure what you're trying to do,
exactly, so I don't know if it solves the problem.

$x = Proc.new { 5 + 5 }

  class C
    def initialize
    end
  end

  C.module_eval {
    def ten
      $x.call
    end
  }

  c = C.new
  puts c.ten()

--
Ned Konz
http://bike-nomad.com
GPG key ID: BEEA7EFE



Fri, 07 Jan 2005 02:45:27 GMT  
 module_eval: adding a method to a class with a proc
Hi,

At Mon, 22 Jul 2002 03:43:26 +0900,

Quote:

> You've got a scoping problem, and x isn't visible inside "def ten".
> This works (I think), but I'm not sure what you're trying to do,
> exactly, so I don't know if it solves the problem.

Alternative.

C.module_eval {
  define_method(:ten, x)

Quote:
}

--
Nobu Nakada


Fri, 07 Jan 2005 03:36:32 GMT  
 module_eval: adding a method to a class with a proc

Quote:

> Alternative.

> C.module_eval {
>   define_method(:ten, x)
> }

thanks a million! that worked like a charm.

--
~transami

  _(")_  dobee dobee do...
   \v/  
   ^ ^



Fri, 07 Jan 2005 17:35:07 GMT  
 
 [ 4 post ] 

 Relevant Pages 

1. automatically adding a pre and post method for all class methods and attributes

2. Adding methods to classes

3. Adding methods into File declaration class ?

4. adding method to existing class

5. Adding new method to Built-In class

6. #59 Add fsync method to IO class

7. Adding a method to a class at the top-level

8. Ruby is cool (adding methods to base classes)

9. Add method to class

10. Dynamically add methods to classes?

11. automatically adding a pre and post method for all class me

12. Adding methods to an existing class??

 

 
Powered by phpBB® Forum Software