详解Ruby中的代码块及其参数传递

2019-09-25 09:37:18于海丽

def nTime(n) 
 (0..n).each {|v| yield(v)} 
end 
nTime(9) do |v| 
 print "#{v} " 
end 

我们来看下Array中的find实现

class Array 
 def find 
  for i in 0...size 
   value = self[i] 
   return value if yield(value) 
  end 
  return nil 
 end 
end 
[1, 3, 5, 7, 9].find {|v| v > 5 } #实现查找第一个大于5的数,输出7。

 因为块的出现,Ruby中少了许多for语句,代码看上去更人性化,写代码不再是枯燥的事,而是一种享受。

四,传递块的另一种方式

def fun #不带参数的 
 yield 
end 
proc = ->{p 'haha'} 
 
fun &proc 
##### 
def fun2(x) #带参数的 
 yield x 
end 
proc2 = ->(x){p x} 
fun2 1,&proc2 

五,instance_eval()和instance_exec()
在Ruby中,提供了一个非常酷的特性,可以通过使用Objec#instance_eval(), Objec#instance_exec()方法插入一个代码块,做一个的对象上下文探针(Context Proble),深入到对象中的代码片段,对其进行操作。有了这个特性以后,就可以很轻松的测试对象的行为,查看对象的当前状态。

class MyClass 
 def initialize 
  @v = 1; 
 end 
end 
obj = MyClass.new 
obj.instance_eval do 
 puts self       # => #<MyClass:0x007fbb2d0299b0> 
 puts @v        # => 1 
end 
obj.instance_exec(5) { |x| puts x * @v } # => 5