目录
Proc 与lambda
#!/usr/bin/ruby
#encoding:UTF-8
numSum = Proc.new do
|x|
result=0
x.each do |n|
result+=n
end
result
end
puts numSum.call([11,22,33])
66
------------------
(program exited with code: 0)
[maisipu@fedora learn]$
#!/usr/bin/ruby
#encoding:UTF-8
numSum = lambda do
|x|
result=0
x.each do |n|
result+=n
end
result
end
puts numSum.call([11,22,33])
#!/usr/bin/ruby
#encoding:UTF-8
numSum = lambda do
|x , y|
result=0
x.each do |n|
result+=n*y
end
result
end
puts numSum.call([11,22,33],3)
#!/usr/bin/ruby
#encoding:UTF-8
numSum = Proc.new do
|x , y|
result=0
x.each do |n|
result+=n*y
end
result
end
puts numSum.call([11,22,33],3)
#!/usr/bin/ruby
#encoding:UTF-8
numSum = lambda do
|x,y|
result=0
x.each do |n|
result+=n*y
end
result
end
puts numSum.call([11,22,33],3)
lambda传参数时注意不能少参数
#!/usr/bin/ruby
#encoding:UTF-8
numSum = lambda do
|x,y|
result=0
x.each do |n|
result+=n*y
end
result
end
puts numSum.call([11,22,33])
[maisipu@fedora learn]$ /bin/sh /tmp/geany_run_script_PABB71.sh
learn4.rb:5:in `block in <main>': wrong number of arguments (given 1, expected 2) (ArgumentError)
from learn4.rb:14:in `<main>'
Proc在有些情况可以少参数
#!/usr/bin/ruby
#encoding:UTF-8
numSum = Proc.new do
|x,y|
if y==nil
y=0
end
x+y
end
puts numSum.call(11)
[maisipu@fedora learn]$ /bin/sh /tmp/geany_run_script_Y2K861.sh
11
另外,下面中代码没问题
#!/usr/bin/ruby
#encoding:UTF-8
numSum = lambda do
|x,y|
if y==nil
y=0
end
return x+y
end
puts numSum.call(11,22)
但换成Proc块就不行
#!/usr/bin/ruby
#encoding:UTF-8
numSum = Proc.new do
|x,y|
if y==nil
y=0
end
return x+y
end
puts numSum.call(11,22)
因为Proc块的return 会直接退出运行块的程序,而lambda只是返回运行它的程序,继续。
传引用
不能通过普通方式实现传引用,不一定是想的那样。
#!/usr/bin/ruby
#encoding:UTF-8
numSum = lambda do
|x,y,result|
result=x+y
end
result=0
numSum.call(11,22,result)
puts result
#!/usr/bin/ruby
#encoding:UTF-8
numSum = Proc.new do
|x,y,result|
result=x+y
end
result=0
numSum.call(11,22,result)
puts result
[maisipu@fedora learn]$
[maisipu@fedora learn]$ /bin/sh /tmp/geany_run_script_H3P861.sh
0
只能通过数组或HASH传引用
#!/usr/bin/ruby
#encoding:UTF-8
numSum = Proc.new do
|x,y,result|
result[0]=x+y
end
result=[0]
numSum.call(11,22,result)
puts result
标签:bin,web,end,do,疑难,result,11,Ruby,numSum
From: https://www.cnblogs.com/waterruby/p/17515377.html