在ruby中,对于以问号结尾的方法名称,真实性是惯用法吗? [英] In ruby, is truthiness idiomatic for a method name ending with a question mark?

查看:128
本文介绍了在ruby中,对于以问号结尾的方法名称,真实性是惯用法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

带问号的方法返回真值(例如,数字)以表示真值,还是应该返回true本身,这是正常的吗?

Is it normal for methods with a question mark to return something that's truthy (for example, a number) to indicate that something is true, or should true itself be returned?

例如,在Ruby标准库或Rails中是否使用了真实性示例?

Are there any examples of truthiness being used in the Ruby standard library or by Rails, for example?

背景:有人在

Background: Someone wrote a String#int? method in an answer to a separate question, which returned an integer to represent true, and nil to represent false. Another user was surprised at not returning a boolean.

推荐答案

对于以?结尾的方法来说,返回truefalse的方法通常是 ,但它不是系统的,没有核心方法会假定它.

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.

核心类中的一个示例是Numeric#nonzero?,其中从不返回truefalse.

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

42.nonzero? # => 42

Set也具有add?delete?.我希望Enumerable#one?返回nilfalse来区分计数为零和大于1的情况.

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.

比较运算符(<>,...)通常是只返回truefalse的示例.这里再次存在Module运算符的异常,当两个模块不相关时,它们将返回nil:

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

这篇关于在ruby中,对于以问号结尾的方法名称,真实性是惯用法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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