开发者

How can I avoid truthiness in 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_boo开发者_如何学Cl # => 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.


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜