方法是一个有名的代码块。是与一个或者多个对象相关联的參数化代码。
调用方法时必需要给出方法名、所在对象(接受者),以及零个或者多个參数值,方法中最后一个表达式的值将作为方法调用的返回值。
代码块不是ruby可操作的对象。一般我们用一个Proc对象代表一个代码块。
有两种方式的Proc对象,一种是proc。一种是lambda,他们都是闭包:他们会保持定义时所在范围内的局部变量,即使在外部范围被调用时。他们也能够对这些变量进行訪问。
方法的定义就不说了。前面有说过。
方法名以小写字母开头。假设方法名超过一个字母,一般用下划线切割开来。
普通情况下,假设參数超过一个,最好不要省略圆括号。
有人说yield就充当一个占位符的作用,函数先给一个占位符,这个函数如同一个纯需函数一样不能直接调用,必须用block把这个位坑给添了才干使用这个函数。
def block_test(num) if block_given? #yield #无參数 yield (num) else puts num end end #block_test(1) #block_test(2) { puts "this is a block ..."} block_test(2) {|x| puts x * 2}
def proc_test(num,&b) if block_given? #b.call b.call(num * 3) else puts "no block" end end #proc_test(1) #proc_test(1) {puts "this is a block"} proc_test(1) {|x| puts x * 2}
Proc对象有proc方式、lambda方式。
假设Proc.new带參数。返回一个关联代码块的Proc对象,这个对象代表这个关联的代码块。
p = Proc.new { puts "hello,dear..."} def proc_test(&pp) pp.call end
puts lambda{|x| x + 10}.call(2)
代码块,proc。lambda的return
一个代码块中的return语句不仅会从调用代码块的迭代器中返回,还会从调用迭代器的的方法中返回。
def test puts "start.." 2.times {puts "hello,";return} puts "end..." #不会别打印 end
def pro_fun (msg) puts "start..." p = Proc.new {puts "hello,#{msg}";return} #会从代码块所在的方法pro_fun中返回 p.call puts "end..." end def lambda_fun(msg) puts "start.." lam = lambda {puts "hello,#{msg}";return} #只返回自身 lam.call puts "end..." end def test puts "test start" #pro_fun "song" lambda_fun "song" puts "test end" end test
原文:http://www.cnblogs.com/bhlsheji/p/5259871.html