Why Treat 0 as True in Ruby?

前端 未结 3 951
庸人自扰
庸人自扰 2020-12-30 19:45

I\'m reading through the excellent Ruby on Rails Tutorial and have encountered the following code.

if 0
  true
else
  false
end

The above r

相关标签:
3条回答
  • 2020-12-30 20:02

    In ruby, if exists, it's true. If not, it's false.

    so, with Ruby null(no address assigned) and false are only false.

    All others are true because it has address assigned to it.

    I think of this way; "Does it exist?"

    0 讨论(0)
  • 2020-12-30 20:07

    In Common Lisp, 0 is also treated as true. For example, the following code returns true.

    (if 0 'true 'false)
    

    No doubt, Ruby is following the same design decision made in Lisp. In Lisp, only an empty list (represented by nil) is false.

    0 讨论(0)
  • 2020-12-30 20:21

    I'm guessing that Matz wanted conceptual simplicity of "truthiness" as such - the only "false" values are false and nil. Period.

    Using just false would be the cleanest but there is understandable need for including nil. To include the integer zero as a special case might open the mental floodgates of questioning truthiness of other types. What about strings, is "" false? And arrays, is [] false? And hashes, is {} false? Ad insanitum (see JavaScript)...

    0 讨论(0)
提交回复
热议问题