什么是私有方法Object#select?

What is the private method Object#select?

和其他许多人一样,我看到了异常

private method 'select' called for nil:NilClass (NoMethodError)

过去。让我感到奇怪的是它没有说 undefined method 'select' for nil:NilClass (NoMethodError)。确实有这种方法,而且是私有的!

这是什么方法?

我发现它是在 Object 上定义的,而不仅仅是 NilClass,但它没有在 BasicObject 上定义。通过使用 #send,我发现它需要 1..4 个参数。前三个必须是数组(或 nil)。最后一个必须可以转换为 "time interval"。无论如何,当它不抛出参数错误时,它就会挂起。

它不在 ruby 文档中,因为它是私有的。我真的不知道如何阅读 C 源代码,也无法在那里找到任何建议。我希望在 object.c;

中看到类似以下行的内容
rb_define_private_method(rb_cObject, "select", select, 0);

可惜,我做不到。

这是什么方法?

内核模块 Kernel#select. Per the docs:

The Kernel module is included by class Object, so its methods are available in every Ruby object.

如果您想知道 select 的作用:

select(read_array [, write_array [, error_array [, timeout]]]) → array or nil

Calls select(2) system call. It monitors given arrays of IO objects, waits until one or more of IO objects are ready for reading, are ready for writing, and have pending exceptions respectively, and returns an array that contains arrays of those IO objects.

您可以在这个问题的答案中阅读更多有关对象包含内核的原因的背景信息:

您可以使用 Object#method and Method#owner:

检查方法的来源
nil.method(:select)
#=> #<Method: NilClass(Kernel)#select>
nil.method(:select).owner
#=> Kernel

原来是Kernel#select