Ruby: How to convert a string to boolean

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

    A gem like https://rubygems.org/gems/to_bool can be used, but it can easily be written in one line using a regex or ternary.

    regex example:

    boolean = (var.to_s =~ /^true$/i) == 0
    

    ternary example:

    boolean = var.to_s.eql?('true') ? true : false
    

    The advantage to the regex method is that regular expressions are flexible and can match a wide variety of patterns. For example, if you suspect that var could be any of "True", "False", 'T', 'F', 't', or 'f', then you can modify the regex:

    boolean = (var.to_s =~ /^[Tt].*$/i) == 0
    

提交回复
热议问题