03月07, 2007

初识lambda

lamda{||block} ->aProc

Kernel::Proc的同义语 lamda{block} 等价于 proc{block}

例子:

print "(t)imes or (p)lus: "
times = gets
print "number: "
number = Integer(gets)


if times =~ /^t/
calc = lambda {|n| n*number }
else
calc = lambda {|n| n+number }
end

puts((1..10).collect(&calc).join(", "))

15:39 2008-3-17 补充

Python中的lambda:

def make_repeater(n):
     return lambda s: s*n

twice = make_repeater(2)
print twice("word")
c:> wordword

Python中的lambda只能使用expression,不能使用statement

本文链接:http://aztack.wang/post/meet-lambda-in-ruby.html

-- EOF--

Comments

评论加载中...

注:如果长时间无法加载,请针对 disq.us | disquscdn.com | disqus.com 启用代理。