为什么在Ruby中使0为True? [英] Why Treat 0 as True in Ruby?

查看:172
本文介绍了为什么在Ruby中使0为True?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读优秀的 Ruby on Rails教程,并遇到以下代码。

 如果0 
true
else
false
end

上述内容返回 true ,并说明与许多语言不同(C是明显的示例),ruby将 0 作为 true 。我认为,不要将这种行为视为特殊的行为,而是认为这是很大的偏离公约的原因。例如,Python可以将 0 视为 False ,就像预期一样。


简而言之,设计红宝石的理由是将 0 作为 true

解决方案

我猜,马茨想要简单的概念简单 - 唯一的假值是 false nil



仅使用 false 将是最干净的,但可以理解的是包含。将整数零包含为特殊情况可能会打开其他类型的真实性质疑的精神障碍。字符串怎么样,是 false?而数组是 [] false?而哈希是 {} false?广告内容(见JavaScript)...


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

if 0
  true
else
  false
end

The above returns true and illustrates how unlike many languages (C being the obvious example), ruby treats 0 as true. Rather than dismiss the behavior as idiosyncratic, I assume there is a good reason for this significant departure from convention. Python, for instance, treats 0 as False, just as one would expect.

In short, what is the rationale in designing ruby to treat 0 as true?

解决方案

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)...

这篇关于为什么在Ruby中使0为True?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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