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/
^ ^

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()

···

On Sunday 21 July 2002 11:17 am, Tom Sawyer wrote:

x = Proc.new { 5 + 5 }

class C
def initialize
end
end

C.module_eval {
def ten
x
end
}


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

Hi,

···

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

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)
}


Nobu Nakada

thanks a million! that worked like a charm.

···

On Sun, 2002-07-21 at 13:34, nobu.nokada@softhome.net wrote:

Alternative.

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


~transami

(") dobee dobee do…
\v/
^ ^