[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

local variable and closure

Daniel Schüle

1/30/2006 5:57:00 PM

Hello,

below is one little script that fails at ### <<< line
the output is

Animal has properties
Animal will be speakable
Dog has properties
Dog will be speakable
Duck has properties
Duck will be speakable
../dort.rb:16:in `speak': undefined local variable or method `msg' for
#<Dog:0x401d8da0> (NameError)
from ./dort.rb:44

I would think that (passed to function) local variable msg would be
"closed" in self.class_eval {} closure and therefor be accessable

can someone point out why it doesn't work?

Regards, Daniel


#!/usr/bin/env ruby

$prop = {}

def prop
puts "#{self.name} has properties"
self.class_eval do
$prop[self] = []
end
end

def speakable(msg)
puts "#{self.name} will be speakable"
self.class_eval do
$prop[self] << "I can speak"
def speak;msg;end ### <<<
end
end

class Animal
prop
speakable "..."
def whatCanIDo;$prop[self.class];end
def self.whatCanIDo;$prop[self];end
end

class Dog < Animal
prop
speakable "wuff"
end

class Duck < Animal
prop
speakable "quak"
end

a = Dog.new
b = Duck.new

puts a.speak, b.speak