In ruby, is truthiness idiomatic for a method name ending with a question mark?

后端 未结 4 1970
情深已故
情深已故 2021-02-13 21:33

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 b

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-13 22:29

    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
    

提交回复
热议问题