如何避免Ruby中的真实性? [英] How can I avoid truthiness in Ruby?

查看:92
本文介绍了如何避免Ruby中的真实性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中是否有任何避免真实性的标准方法,或者我需要推出自己的解决方案,例如

Is there any standard way to avoid truthiness in Ruby, or would I need to roll my own solution, such as

class FalseClass
  def to_bool
    self
  end
end

class TrueClass
  def to_bool
    self
  end
end

true.to_bool # => true
false.to_bool # => false
nil.to_bool # => NoMethodError
42.to_bool # => NoMethodError

背景:我知道to_bool会违背Ruby的宽容性,但是我正在研究三元逻辑,并希望避免意外地执行类似的操作

Background: I know that to_bool would go against the permissive nature of Ruby, but I'm playing around with ternary logic, and want to avoid accidentally doing something like

require "ternary_logic"
x = UNKNOWN
do_something if x

我正在使用三元逻辑,因为我正在编写一个室友共享网站的解析器(供个人使用,而非用于商业用途),并且某些字段可能会丢失信息,因此这是未知的这个地方是否符合我的标准.但是,我会尝试限制使用三元逻辑的代码量.

I'm using ternary logic because I'm writing a parser of a flatmate-share web site (for personal, not commercial, use) and it's possible for some fields to be missing information, and therefore it'd be unknown whether the place meets my criteria or not. I'd try to limit the amount of code that uses the ternary logic, however.

推荐答案

在Ruby中不可能影响真实性或虚假性. nilfalse都是虚假的,其他所有东西都是真实的.

It is not possible to influence truthiness or falsiness in Ruby. nil and false are falsy, everything else is truthy.

此功能每两年左右出现一次,但始终被拒绝. (出于我个人不令人信服的原因,但我不是做主的人.)

It's a feature that comes up every couple of years or so, but is always rejected. (For reasons that I personally don't find convincing, but I'm not the one calling the shots.)

您将必须实现自己的逻辑系统,但不能禁止某人在未知值上使用Ruby的逻辑运算符.

You will have to implement your own logic system, but you cannot prohibit someone from using Ruby's logical operators on an unknown value.

我一次重新实现了Ruby的逻辑系统,这很有趣并且证明可以做到.将其扩展到三元逻辑应该相当容易. (写这篇文章时,我实际上是从RubySpec进行了一致性测试,并且将它们移植到了我的实现中,它们都通过了,因此我相当有信心,它符合Ruby的语义.)

I re-implemented Ruby's logic system once, for fun and to show it can be done. It should be fairly easy to extend this to ternary logic. (When I wrote this, I actually took the conformance tests from RubySpec and ported them to my implementation, and they all passed, so I'm fairly confident that it matches Ruby's semantics.)

这篇关于如何避免Ruby中的真实性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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