Ruby: How to convert a string to boolean

前端 未结 14 797
抹茶落季
抹茶落季 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:55

    Don't think too much:

    bool_or_string.to_s == "true"  
    

    So,

    "true".to_s == "true"   #true
    "false".to_s == "true"  #false 
    true.to_s == "true"     #true
    false.to_s == "true"    #false
    

    You could also add ".downcase," if you are worried about capital letters.

    0 讨论(0)
  • 2020-12-08 13:56

    If you use Rails 5, you can do ActiveModel::Type::Boolean.new.cast(value).

    In Rails 4.2, use ActiveRecord::Type::Boolean.new.type_cast_from_user(value).

    The behavior is slightly different, as in Rails 4.2, the true value and false values are checked. In Rails 5, only false values are checked - unless the values is nil or matches a false value, it is assumed to be true. False values are the same in both versions: FALSE_VALUES = [false, 0, "0", "f", "F", "false", "FALSE", "off", "OFF"]

    Rails 5 Source: https://github.com/rails/rails/blob/5-1-stable/activemodel/lib/active_model/type/boolean.rb

    0 讨论(0)
提交回复
热议问题