foo(& nil)与foo(&"not proc")的行为有何不同? [英] How does foo(&nil) behave differently than foo(&"not a proc")?

查看:72
本文介绍了foo(& nil)与foo(&"not proc")的行为有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从he中发现

[1, 2, 3].each(&nil)

不会引起任何错误-它只会返回一个枚举数.

doesn't cause any errors - it just returns an enumerator.

通过对比,

[1, 2, 3].each(&"")

提高

TypeError: wrong argument type String (expected Proc)

此外,&nil是否导致block_given?返回假

Also, &nil causes block_given? to return false

def block_given_tester
  if block_given?
    puts "Block given"
  else
    puts "Block not given"
  end
end

block_given_tester(&nil) # => Block not given

不是因为NilClass实现了to_proc-我检查了RDoc.

It's not because NilClass implements to_proc - I checked the RDoc.

我可以理解为什么拥有&nil会很好,但是我不确定如何完成.这是nil具有其他对象未共享的特殊行为的方式之一吗?

I can understand why it'd be nice to have &nil, but I'm not sure how it's done. Is this just one of the ways nil has special behavior not shared by other objects?

推荐答案

可以通过查看Ruby的源代码找到答案.

The answer can be found by looking at Ruby's source code.

Ruby 1.8:

查看文件eval.c中的功能block_pass.请注意,它专门从Proc对象(宏NIL_P)处理nil.如果函数传递了一个nil值,它将计算一个空块(我认为)并返回.之后的代码将检查对象是否为Proc对象(函数rb_obj_is_proc),如果不是,则会引发异常错误的参数类型(期望的Proc)".

Look at the function block_pass in the file eval.c. Note that it treats nil specially from Proc objects (the macro NIL_P). If the function is passed a nil value, it evaluates an empty block (I think) and returns. The code right after it checks whether the object is a Proc object (the function rb_obj_is_proc) and raises the exception "wrong argument type (expected Proc)" if it isn't.

Ruby 1.9.2:

Ruby 1.9.2:

查看文件vm_insnhelper.c中的方法caller_setup_args.仅使用to_proc转换proc 如果不是零;否则,将绕过类型转换和类型检查.

Look at the method caller_setup_args in the file vm_insnhelper.c. It converts the proc with to_proc only if it is not nil; otherwise, the type conversion and type check are bypassed.

这篇关于foo(& nil)与foo(&"not proc")的行为有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆