如何避免 Ruby 中的真实性?
是否有任何标准方法可以避免 Ruby 中的真实性,或者我需要推出自己的解决方案,例如
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
Background: 我知道 to_bool
会违背 的宽容本质Ruby,但我正在玩三元逻辑,并且希望避免意外地做类似
require "ternary_logic"
x = UNKNOWN
do_something if x
我正在使用三元逻辑的事情,因为我正在编写一个室友共享网站的解析器(供个人使用,而不是商业用途)并且某些字段可能会缺少信息,因此不知道该地点是否符合我的标准。然而,我会尝试限制使用三元逻辑的代码量。
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
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不可能影响 Ruby 中的真实性或虚假性。
nil
和false
是假的,其他都是真的。这个功能每隔几年左右就会出现一次,但总是被拒绝。 (出于我个人不认为令人信服的原因,但我不是发号施令的人。)
您必须实现自己的逻辑系统,但您不能禁止某人对未知值使用 Ruby 的逻辑运算符。
我重新实现了一次 Ruby 的逻辑系统,为了好玩并展示它是可以完成的。将其扩展到三元逻辑应该相当容易。 (当我写这篇文章时,我实际上从 RubySpec 进行了一致性测试,并将它们移植到我的实现中,而且它们都通过了,所以我相当有信心它符合 Ruby 的语义。)
It is not possible to influence truthiness or falsiness in Ruby.
nil
andfalse
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.)
You will have to implement your own logic system, but you cannot prohibit someone from using Ruby's logical operators on an unknown value.
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.)
您可以利用 1.9 中可重写的
!
运算符和!!
习惯用法来重新定义真实性。让我们有一个Python式的真实:
You can take advantage of the overridable
!
operator in 1.9 and the!!
idiom to redefine truthiness.Let's have a Pythonesque truthiness:
我还用 Ruby 制作了自己的逻辑系统(为了好玩),你可以轻松地重新定义真实性:
请注意,普通条件句的类似物是 if!/else_if!/else!
请参阅:http://github.com/banister/custom_boolean
I also made my own logic system in Ruby (for fun), and you can easily redefine truthiness:
Note, the analogs of the normal conditionals are if!/else_if!/else!
see: http://github.com/banister/custom_boolean