这就是我想要做的:
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传递给原始块,而不是作为变量或任何东西传递,而是像测试示例中那样作为实际块传递.
有小费吗?