这就是我想要做的:
def call_block(in_class = "String", &block)
instance = eval("#{in_class}.new")
puts "instance class: #{instance.class}"
instance.instance_eval{ block.call }
end
# --- TEST EXAMPLE ---
# This outputs "class: String" every time
"sdlkfj".instance_eval { puts "class: #{self.class}" }
# This will only output "class: Object" every time
# I'm trying to get this to output "class: String" though
call_block("String") { puts "class: #{self.class}" }
在它说“instance.instance_eval{block.call}”的那一行,我试图找到另一种方法来让新的实例变量在块上运行实例eval。我能想到的唯一方法是传递 instance_eval 原始块,而不是作为变量或任何东西,而是作为测试示例中的真实块。
有小费吗?