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 报告它是人类?以及可以做什么,以便在调用 Developer.lab 时 proc 报告 Developer。
最佳答案
它很微妙,但它归结为简单地调用 block (在这种情况下它充当一个普通的闭包,并且 self
对应于它被定义的位置,即在 Human
),或(直接)将其用作方法定义或 instance_eval
的 block :
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
关于ruby - 实例评估 : why the class of subclass is superclass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2758513/