How can I avoid truthiness in Ruby?

笑着哭i 提交于 2019-12-29 08:52:13

问题


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.


回答1:


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

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




回答2:


You can take advantage of the overridable ! operator in 1.9 and the !! idiom to redefine truthiness.

Let's have a Pythonesque truthiness:

class Numeric
  def !
    zero?
  end
end

class Array
  def !
    empty?
  end
end

!![] #=> false
!!0 #=> false



回答3:


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!

# redefine truthiness with the `truth_test` method
CustomBoolean.truth_test = proc { |b| b && b != 0 && b != [] }

if!(0) { 
    puts 'true' 
}.
else! { 
    puts 'false' 
}
#=> false

see: http://github.com/banister/custom_boolean



来源:https://stackoverflow.com/questions/3645232/how-can-i-avoid-truthiness-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!