Ruby元编程与JRuby:深入解析与对比
1. Ruby元编程中的闭包
在Ruby中,闭包是一个核心概念,它对于块、lambda和proc的工作方式至关重要,同时也适用于像 eval
、 instance_eval
和 define_method
这样的方法。
1.1 方法作为闭包
下面通过一个示例来展示如何使用闭包访问实例变量和周围环境。
class Quote
def initialize
@str = "The quick brown fox"
end
end
def create_method_using_a_closure
str2 = "jumps over the lazy dog."
Quote.send(:define_method, :display) do
puts "#{@str} #{str2}"
end
end
create_method_using_a_closure
Quote.new.display
在上述代码中, define_method
是 Module
类的私有方法,因此使用了 send
语法来调用它。 str2
变量在 create_method_using_a_closure
方法返回后,仍然会被保存在堆中,供新方法使用。