12

带有问号的方法返回真实的东西(例如,一个数字)以表明某事是真实的,或者true本身应该返回,这是否正常?

例如,在 Ruby 标准库或 Rails 中是否有任何真实性的例子?

背景:有人在一个单独的问题的答案中String#int?写了一个方法,它返回一个整数来表示真,并表示假。另一位用户对没有返回布尔值感到惊讶。nil

4

4 回答 4

8

添加一个?在 Ruby 中为方法名称添加一个惯用的方法是该方法将返回 true 或 false。对象#nil?是一个很好的例子。事实上,Object 有很多真实性检查的好例子。

于 2010-11-27T01:40:09.273 回答
6

It is usual for methods ending with ? to return either true or false but it is not systematic and no core method will assume it.

An example in the core classes is Numeric#nonzero? which never returns true or false.

42.nonzero? # => 42

The library Set has add? and delete? too. I wish Enumerable#one? returned nil or false to distinguish cases where the count is zero from when it is greater than one.

A similar example are the comparison operators (<, >, ...), which usually return only true or false. Here again exceptions exist for Module's operators that will return nil instead when the two modules are not related:

Array > Enumerable  # => false
Array > Fixnum      # => nil
于 2010-11-28T11:15:58.437 回答
2

您的问题有两个答案,并且都是有效的:

从技术上讲,在进行条件测试时,任何返回 afalsenil值的东西都充当 false 布尔值,就像非 nil 或true值充当 true 一样。因此,在您想知道某物是否为整数的大多数情况下,所讨论的方法都可以正常工作。

但从风格上讲,一种以“?”结尾的方法 应该返回一个布尔值truefalse仅返回那些。

所讨论的方法并不能很好地满足我们的期望,并且未能通过 POLS(“最小意外原则”),因为您可以合理地期望返回一个布尔值,并得到一个整数或零。nil当代码因意外或 Fixnum 值而失败时,这可能会导致代码中出现令人不快的意外。

所以,虽然它是一种有效的方法,但它不是一个方法,我会在代码审查中提出它。这导致了一个单独的讨论,即此类微妙的事情如何增强或损害代码维护,但这是一个完全不同的讨论。

于 2010-11-27T02:53:48.820 回答
2

I renamed the method in question to remove the ?, which was really not important to the question being answered. Scanning through the core functions that end in ?s, the only ones I spotted that returned data or nil were the add? and delete? methods on Set.

于 2010-11-27T03:07:20.887 回答