访问次数
我的另一个总结性博客: todototry 大米粒

ruby method lambda block proc 联系与区别 --- next break return

$res = "__"

def lamb(&lamb)

3.times do
puts $res
=lamb.call
end
puts
"-------at the end of lamb() : #{$res}"
end

def lamb_test
lamb {
return puts " return in lamb() " }
puts
"--------at the lamb_test() end"
end


def bl
3.times do
puts $res
= yield
end
puts
" ------at the end of bl() :#{$res}"
end

def bl_test
bl do
return puts "use return in bl()" end
puts
"-----at the end of test_test()"
end


def p(&pro)
3.times do
puts $res
= pro.call
end
puts
"-----at the end of p() : #{$res}"
end

def p_test
p do
return puts "use return in p() of p_test()" end
puts
"-----at the end of p_test()"
end



puts
"-------------lambda----------"
nextt
= lambda{ next "next in lamb()"; puts "behind next" }
breakk
= lambda{ break "break in in lamb()";puts "behind break" }
ret
= lambda{ break "return in in lamb()";puts "behind return" }
lamb(
&nextt)
lamb(
&breakk)
lamb(
&ret)
lamb_test


puts
"\n----------------block--------"
bl { next
"next in bl()" ; puts "behind next" }
bl {
break "break in bl() " ;puts "behind break" }
#bl { return "return in bl() " ;puts "behind return" }
bl_test

puts
"\n-----------proc------------"
ne
= Proc.new { next "next in p() "; puts "behind next" }
br
= Proc.new { break "break in p() " ;puts "behind break" }
#retu = Proc.new { return "return in p() " ;puts "behind return" }
p(&ne)
#p(&br)
#
p(&retu)
p_test

  

 

运行结果:

-------------lambda----------

next  in lamb()

next  in lamb()

next  in lamb()

-------at the end of lamb() : next  in lamb()

break in in lamb()

break in in lamb()

break in in lamb()

-------at the end of lamb() : break in in lamb()

return in in lamb()

return in in lamb()

return in in lamb()

-------at the end of lamb() : return in in lamb()

 return in lamb() 

----------------block--------

next in  bl()

next in  bl()

next in  bl()

 ------at the end of bl() :next in  bl()

use return in bl()

-----------proc------------

next in p() 

next in p() 

next in p() 

-----at the end of  p() : next in p() 

use return in p() of p_test()

解释下

Method :方法

lambda:匿名方法

block:代码段

proc:有名block

Method:普通函数

lambda:匿名函数,内部的return 不会 退出上级 的代码。

block:无名代码片段,内部的return 会 退出上级代码。

proc:具名(有名)代码片段,内部的return 会 退出上级代码。

内部关键字:

next   break   和   return 的区别

lambda表达式中 next :返回给调用它的函数,不会退出调用它的函数。

lambda表达式中 break:与next没差别好像

lambda表达式中 return :与next没差别好像

block表达式中 next : 

block表达式中 break: 

block表达式中 return :退出调用它的函数

proc表达式中 next :返回给调用它的函数。

proc表达式中 break:与next没差别好像

proc表达式中 return :

posted @ 2011-08-14 17:01  fandyst  阅读(639)  评论(1编辑  收藏  举报