ruby 中 block 的使用方法


对包含代码的字符串和block求解。
Ruby提供了多种不同类型的求解方式:eval、instance_eval和class_eval。

class_eval  可以在一个类的定义或者module定义的上下文中对给定字符串或block进行求解。我们常常用class_eval来向类的定义中加入方法,或是包含其他的module。

klass = Class.new
klass.class_eval do
def encoded_hello
htnl_escape "Hello World"
end
end
klass.new.encoded_hello #=> Hello World

不使用class_eval也可以达到上面的效果,但是要牺牲代码的可读性。

klass = Class.new
klass.send :define_method, :encoded_hello do
html_escape "Hello World"
end
klass.send :public, :encoded_hello
klass.new.encoded_hello #=> Hello World


使用Object的instance_eval方法,可以在一个类实例的上下文中对给定字符串或block进行求解。这是个功能强大的概念:你可以先在任何上下文中创建一块代码,然后在一个单独的对象实例的上下文中对这块代码进行求解。为了设定代码执行的上下文,self变量要设置为执行代码时所在的对象实例,以使得代码可以访问对象实例的变量。

class Navigator
def initialize
@page_index = 0
end
def next
@page_index += 1
end
end
navigator = Navigator.new
navigator.next
navigator.next
navigator.instance_eval "@page_index" #=> 2
navigator.instance_eval { @page_index } #=> 2

使用Kernel的eval方法可以在当前上下文中对一个字符串求解。可以选择为eval方法制定一个binding对象。如果给定了一个binding对象,求解的过程会在binding对象的上下文中执行。

hello = "hello world"
puts eval("hello") #=> "hello world"
proc = lambda { hello = "goodbye world"; binding }
eval("hello", proc.call) #=> "goodbye world"

http://tech.it168.com/d/2007-09-07/200709071737579.shtml

猜你喜欢

转载自fujinbing.iteye.com/blog/1127288
今日推荐