Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 443
Andrew Grimm Avatar asked Dec 09 '22 14:12

Andrew Grimm


1 Answers

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

like image 124
Jörg W Mittag Avatar answered Dec 27 '22 13:12

Jörg W Mittag