def singleton_class
class << self
self
end
end
class Human
proc = lambda { puts 'proc says my class is ' + self.name.to_s }
singleton_class.instance_eval do
define_method(:lab) do
proc.call
end
end
end
class Developer < Human
end
Human.lab # class is Human
Developer.lab # class is Human ; oops
以下解决方案有效。
def singleton_class
class << self
self
end
end
class Human
proc = lambda { puts 'proc says my class is ' + self.name.to_s }
singleton_class.instance_eval do
define_method(:lab) do
self.instance_eval &proc
end
end
end
class Developer < Human
end
Human.lab # class is Human
Developer.lab # class is Human ; oops
为什么Developer.lab报告它是Human?还有什么可以让proc在调用Developer.lab时报告Developer。
答案 0 :(得分:4)
闭包是在定义它的上下文中捕获 self - 就像闭包应该做的那样。因此,当它被调用时,它将使用对它捕获的上下文的引用。闭包不是定义预期功能的理想工具。而不是proc.call,“define_method”调用的内容应该是“puts”,proc表示我的类是'+ name.to_s“
答案 1 :(得分:4)
它很微妙,但归结为简单地调用块(在这种情况下,它充当正常闭包,self
对应于它的定义位置,即在Human
),或使用它(直接)作为方法定义的块或instance_eval
:
def singleton_class
class << self
self
end
end
class Human
PROC = proc { puts 'proc says my class is ' + self.name.to_s }
singleton_class.instance_eval do
define_method(:lab) do
PROC.call
end
define_method(:lab2, &PROC.method(:call))
define_method(:lab3) do
instance_eval(&PROC)
end
define_method(:lab4, &PROC)
end
end
class Developer < Human
end
Human::PROC.call # => "class is Human" (original closure)
Developer.lab # Same as previous line, so "class is Human" (original closure)
Developer.lab2 # ditto
Developer.instance_eval(&Human::PROC) # => "class is Developer" (instance_eval changes sets a different scope)
Developer.lab3 # Same as previous line, so "class is Developer"
Developer.lab4 # ditto
答案 2 :(得分:1)
我必须考虑一下为什么这是有效的,但目前它 的工作:
class Human
proc = -> { name }
define_singleton_method(:lab, &proc)
end
class Developer < Human; end
require 'test/unit'
class TestClosures < Test::Unit::TestCase
def test_that_the_human_class_is_named_human
assert_equal 'Human', Human.lab
end
def test_that_the_developer_class_is_named_developer
assert_equal 'Developer', Developer.lab
end
end