简体   繁体   English

混淆与`call`到`block`创建为`Proc`对象

[英]Confusion with `Call` to `block` created as `Proc` object

I have created an object calling Proc.new and passing to it a block as an argument: 我创建了一个调用Proc.new的对象,并将一个块作为参数传递给它:

a = Proc.new{|x| x = x*10; puts(x)}
#=> #<Proc:0xd26fd8@(irb):3>
a.call(10)
#100
#=> nil
a.call(10,20)
#100
#=> nil
a.call(10,20,40)
#100
#=> nil

I didn't use any splat operator(*) also. 我也没有使用任何splat operator(*) But how does then block parameter x being able to ignore the extra arguments? 但是如何阻止参数x能够忽略额外的参数呢?

When we do the same we get a definite error, but why that's not the case with block parameter? 当我们这样做时,我们得到一个明确的错误,但为什么不是块参数的情况?

def show(x)
print "X::#{x}"
end
#=> nil
show(10)
#X::10#=> nil
show(10,20)
#ArgumentError: wrong number of arguments (2 for 1)
#        from (irb):6:in `show'
#        from (irb):10
#        from C:/Ruby193/bin/irb:12:in `<main>'

Procs convert missing arguments to nil whereas lambda does not. Procs将缺少的参数转换为nil,而lambda则不。

If you want to be tolerant about errors then use Procs. 如果您想容忍错误,请使用Procs。 Otherwise you'll want to go with lambda 否则你会想要使用lambda

l = ->(x) { x = x * 10; puts x }
=> #<Proc:0x007fada3be9468@(pry):12 (lambda)>
l.call(10, 20)
ArgumentError: wrong number of arguments (2 for 1)
from (pry):12:in `block in <main>'

That's how Procs work, internally, they don't care if too much arguments are passed. 这就是Procs在内部工作的方式,他们并不关心是否传递了太多的论据。

Proc#call will take an array of arguments and bind them to the arguments of the block, and won't complain if the count does not match. Proc#call将获取一组参数并将它们绑定到块的参数,并且如果计数不匹配则不会抱怨。

Proc Lambdas, however, will complain about it, that's one of the differences between them and regular Procs : 然而,Proc Lambdas会抱怨它,这是它们和常规过程之间的区别之一:

2.0.0p0 :006 > r = lambda { |x| puts x }
 => #<Proc:0x007fac6913b600@(irb):6 (lambda)>
2.0.0p0 :007 > r.call(1,2)
ArgumentError: wrong number of arguments (2 for 1)
from (irb):6:in `block in irb_binding'
from (irb):7:in `call'
from (irb):7
from /Users/Intrepidd/.rvm/rubies/ruby-2.0.0-p0/bin/irb:16:in `<main>'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM