Ruby: How to convert a string to boolean

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

    In Rails I prefer using ActiveModel::Type::Boolean.new.cast(value) as mentioned in other answers here

    But when I write plain Ruby lib. then I use a hack where JSON.parse (standard Ruby library) will convert string "true" to true and "false" to false. E.g.:

    require 'json'
    azure_cli_response = `az group exists --name derrentest`  # => "true\n"
    JSON.parse(azure_cli_response) # => true
    
    azure_cli_response = `az group exists --name derrentesttt`  # => "false\n"
    JSON.parse(azure_cli_response) # => false
    

    Example from live application:

    require 'json'
    if JSON.parse(`az group exists --name derrentest`)
      `az group create --name derrentest --location uksouth`
    end
    

    confirmed under Ruby 2.5.1

提交回复
热议问题