Ruby: How to convert a string to boolean

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

    Although I like the hash approach (I've used it in the past for similar stuff), given that you only really care about matching truthy values - since - everything else is false - you can check for inclusion in an array:

    value = [true, 'true'].include?(value)
    

    or if other values could be deemed truthy:

    value = [1, true, '1', 'true'].include?(value)
    

    you'd have to do other stuff if your original value might be mixed case:

    value = value.to_s.downcase == 'true'
    

    but again, for your specific description of your problem, you could get away with that last example as your solution.

提交回复
热议问题