Ruby: How to convert a string to boolean

前端 未结 14 799
抹茶落季
抹茶落季 2020-12-08 13:16

I have a value that will be one of four things: boolean true, boolean false, the string \"true\", or the string \"false\". I want to convert the string to a boolean if it i

14条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-08 13:38

    In rails, I've previously done something like this:

    class ApplicationController < ActionController::Base
      # ...
    
      private def bool_from(value)
        !!ActiveRecord::Type::Boolean.new.type_cast_from_database(value)
      end
      helper_method :bool_from
    
      # ...
    end
    

    Which is nice if you're trying to match your boolean strings comparisons in the same manner as rails would for your database.

提交回复
热议问题