Why does Ruby have TrueClass and FalseClass instead of a single Boolean class?

前端 未结 8 878
野趣味
野趣味 2020-12-07 20:16

I was working on serializing values when found out about this one. Ruby has a TrueClass class, and a FalseClass class, but it has no Boolean class. I\'d like to

8条回答
  •  半阙折子戏
    2020-12-07 20:17

    Since everything but false and nil evaluate to true in Ruby by default, you would only need to add parsing to String.

    Something like this could work:

    class Object
    
      ## Makes sure any other object that evaluates to false will work as intended,
      ##     and returns just an actual boolean (like it would in any context that expect a boolean value).
      def trueish?; !!self; end
    
    end
    
    class String
    
      ## Parses certain strings as true; everything else as false.
      def trueish?
        # check if it's a literal "true" string
        return true if self.strip.downcase == 'true'
    
        # check if the string contains a numerical zero
        [:Integer, :Float, :Rational, :Complex].each do |t|
          begin
            converted_number = Kernel.send(t, self)
            return false if converted_number == 0
          rescue ArgumentError
            # raises if the string could not be converted, in which case we'll continue on
          end
        end
    
        return false
      end
    
    end
    

    When used, this would give you:

    puts false.trueish?   # => false
    puts true.trueish?    # => true
    puts 'false'.trueish? # => false
    puts 'true'.trueish?  # => true
    puts '0'.trueish?     # => false
    puts '1'.trueish?     # => true
    puts '0.0'.trueish?   # => false
    puts '1.0'.trueish?   # => true
    

    I believe part of the “big idea” behind Ruby is to just make the behavior you desire inherent to your program (e.g. boolean parsing), rather creating a fully encapsulated class that lives in it's own namespace world (e.g. BooleanParser).

提交回复
热议问题