184

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 is a string, otherwise leave it unmodified. In other words:

"true" should become true

"false" should become false

true should stay true

false should stay false

3
  • 2
    Does the result have to be one of the two values true or false or is it enough if the result is truthy or falsey? If the latter, then false is already falsey, and both true and 'true' are truthy, so the only value for which the result is not already correct, is 'false': if input == 'false' then true else input end should do it. Mar 25, 2016 at 22:58
  • That's a great comment Jorg, however I would assume that for some applications it is necessary to have the boolean value true or false and not just a value that is truthy or false.
    – emery
    Mar 26, 2016 at 5:00
  • 2
    Emery, if you need to return a boolean you could prepend @Jörg's expression with two "nots": !!(if input == 'false' then true else input end). The second ! converts the return value to a boolean that is the opposite of what you want; the first ! then makes the correction. This " trick" has been around a long time. Not everyone is fond of it. Mar 26, 2016 at 6:54

17 Answers 17

202

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

7
  • 2
    This is helpful, though I wish that the set of FALSE_VALUES in Rails also included "no".
    – pjrebsch
    Nov 11, 2017 at 2:49
  • 10
    @pjrebsch Fairly simple to patch in your app. Just add ActiveRecord::Type::Boolean::FALSE_VALUES << "no" to an initializer.
    – thomasfedb
    Apr 5, 2018 at 16:20
  • 2
    note that ActiveModel::Type::Boolean.new.cast(value) is case sensitive...so 'False' will evaluate to true as will any other string except for 'false'. empty strings '' default to nil, not false. ^^ valuable insight provided here by @thomasfedb on initializer customization
    – frostini
    Aug 21, 2018 at 13:43
  • 3
    ActiveModel::Type::Boolean.new.cast(nil) also returns nil.
    – Nikolay D
    Mar 21, 2019 at 12:11
  • 4
    As of Rails 5.2.4 the method suggested by @thomasfedb no longer works because ActiveRecord::Type::Boolean::FALSE_VALUES is frozen.
    – moveson
    Jan 13, 2020 at 12:37
171
def true?(obj)
  obj.to_s.downcase == "true"
end
8
  • 3
    Yes, @null, the to_s method converts boolean true or false to "true" or "false" and leaves the value unchanged if was originally a string. Now we are certain to have either "true" or "false" as a string... and we just need to use == check if the string is equal to "true". If it is then the original value was either true or "true". If it is not then the original value was false, "false", or something totally unrelated.
    – emery
    Dec 28, 2017 at 21:50
  • 10
    Since the string may be upcased/titled, downcasing will ensure a match: obj.to_s.downcase == 'true'
    – TDH
    Apr 19, 2018 at 19:14
  • 3
    Use downcase! and you'll allocate 1 less object. downcase will duplicate the existing string. When Frozen String Literals becomes a Ruby default option, this will matter less. Mar 28, 2019 at 18:49
  • 1
    I took the liberty of editing the answer to include the suggestion of downcase! as per the above comments. It's less elegant to read, but if you aren't sure what variable types you're working with, more robustness is never bad.
    – emery
    Jun 20, 2019 at 21:03
  • This wont report an error if you feed it bad data, so it's not a great solution if you need any error handling Jul 18, 2019 at 8:57
40

I've frequently used this pattern to extend the core behavior of Ruby to make it easier to deal with converting arbitrary data types to boolean values, which makes it really easy to deal with varying URL parameters, etc.

class String
  def to_boolean
    ActiveRecord::Type::Boolean.new.cast(self)
  end
end

class NilClass
  def to_boolean
    false
  end
end

class TrueClass
  def to_boolean
    true
  end

  def to_i
    1
  end
end

class FalseClass
  def to_boolean
    false
  end

  def to_i
    0
  end
end

class Integer
  def to_boolean
    to_s.to_boolean
  end
end

So let's say you have a parameter foo which can be:

  • an integer (0 is false, all others are true)
  • a true boolean (true/false)
  • a string ("true", "false", "0", "1", "TRUE", "FALSE")
  • nil

Instead of using a bunch of conditionals, you can just call foo.to_boolean and it will do the rest of the magic for you.

In Rails, I add this to an initializer named core_ext.rb in nearly all of my projects since this pattern is so common.

## EXAMPLES

nil.to_boolean     == false
true.to_boolean    == true
false.to_boolean   == false
0.to_boolean       == false
1.to_boolean       == true
99.to_boolean      == true
"true".to_boolean  == true
"foo".to_boolean   == true
"false".to_boolean == false
"TRUE".to_boolean  == true
"FALSE".to_boolean == false
"0".to_boolean     == false
"1".to_boolean     == true
true.to_i          == 1
false.to_i         == 0
2
  • 1
    what about 't' and 'f' 'T' & 'F', 'y' & 'n', 'Y' & 'N'?
    – MrMesees
    Sep 25, 2019 at 10:08
  • 1
    This works too well, eg. Does "buy" begin with a "b"? "buy"=~/b/ => 0 But ("buy"=~/b/).to_boolean => false
    – Marcos
    Apr 9, 2020 at 15:56
33

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.

3
  • 12
    nil.to_s == 'true' #false Feb 13, 2018 at 17:42
  • @juliangonzalez: this was the fact I was missing in all of the other explanations - thank you.
    – anha1979
    Jan 20, 2022 at 19:12
  • nil.to_s == 'false' # false
    – Nick Roz
    Jul 27 at 15:51
33

Working in Rails 5

ActiveModel::Type::Boolean.new.cast('t')     # => true
ActiveModel::Type::Boolean.new.cast('true')  # => true
ActiveModel::Type::Boolean.new.cast(true)    # => true
ActiveModel::Type::Boolean.new.cast('1')     # => true
ActiveModel::Type::Boolean.new.cast('f')     # => false
ActiveModel::Type::Boolean.new.cast('0')     # => false
ActiveModel::Type::Boolean.new.cast('false') # => false
ActiveModel::Type::Boolean.new.cast(false)   # => false
ActiveModel::Type::Boolean.new.cast(nil)     # => nil
3
  • 6
    ActiveModel::Type::Boolean.new.cast("False") # => true ... Use to_s.downcase on your input is a good idea
    – Raphayol
    Apr 1, 2020 at 16:28
  • 1
    Careful: ActiveModel::Type::Boolean.new.cast('fals') # => true ActiveModel::Type::Boolean.new.cast('falso') # => true Oct 8, 2021 at 14:24
  • 3
    @RicardoVillamil why would you need to test if "fals" or "falso" are booleans? Sep 16, 2022 at 10:21
18
if value.to_s == 'true'
  true
elsif value.to_s == 'false'
  false
end
10
  • 10
    Your code as a one-liner value.to_s == 'true' ? true : false Mar 25, 2016 at 22:27
  • 29
    @sagarpandya82 : Never do that, it defeats the purpose of the conditional operator : if true then true, if false then false Guess what? You can completely remove it! value.to_s == 'true' ? true : false should just be value.to_s == 'true' Dec 2, 2016 at 22:08
  • 4
    @EricDuminil absolutely agree, rookie error at the time. Dec 2, 2016 at 22:32
  • 3
    Note that this answer will return nil when the value can't be converted while those one-liners will never fail and always return false unless the value is 'true'. Both are valid approaches and may be the right answer to different situations, but they are not the same.
    – Doodad
    Apr 7, 2018 at 22:42
  • 1
    @AndreFigueiredo the ternary operator doesn't do anything in this case. Try without, and compare the results. Sep 11, 2019 at 23:52
13
h = { "true"=>true, true=>true, "false"=>false, false=>false }

["true", true, "false", false].map { |e| h[e] }
  #=> [true, true, false, false] 
0
10

In a rails 5.1 app, I use this core extension built on top of ActiveRecord::Type::Boolean. It is working perfectly for me when I deserialize boolean from JSON string.

https://api.rubyonrails.org/classes/ActiveModel/Type/Boolean.html

# app/lib/core_extensions/string.rb
module CoreExtensions
  module String
    def to_bool
      ActiveRecord::Type::Boolean.new.deserialize(downcase.strip)
    end
  end
end

initialize core extensions

# config/initializers/core_extensions.rb
String.include CoreExtensions::String

rspec

# spec/lib/core_extensions/string_spec.rb
describe CoreExtensions::String do
  describe "#to_bool" do
    %w[0 f F false FALSE False off OFF Off].each do |falsey_string|
      it "converts #{falsey_string} to false" do
        expect(falsey_string.to_bool).to eq(false)
      end
    end
  end
end
1
  • This is perfect. Exactly what I was looking for.
    – Doug
    Sep 9, 2019 at 19:21
7

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

4

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
3
  • 2
    Note: \A/\z is start/end of string and ^/$ is start/end of line. So if var == "true\nwhatevs" then boolean == true.
    – cremno
    Mar 25, 2016 at 22:53
  • 1
    This really helped me and I like var.eql?('true') ? true : false very much. Thanks!
    – Christian
    Jul 23, 2019 at 11:44
  • 1
    @Christian keep in mind it has to be var.to_s.eql? not just var.eql? otherwise it won't convert a boolean true to string 'true'
    – emery
    Jan 7, 2021 at 21:38
4

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.

4

I have a little hack for this one. JSON.parse('false') will return false and JSON.parse('true') will return true. But this doesn't work with JSON.parse(true || false). So, if you use something like JSON.parse(your_value.to_s) it should achieve your goal in a simple but hacky way.

3

Rubocop suggested format:

YOUR_VALUE.to_s.casecmp('true').zero?

https://www.rubydoc.info/gems/rubocop/0.42.0/RuboCop/Cop/Performance/Casecmp

1
  • I like this answer because it's a one-liner that handles all the cases which were stated in the original question, including capital vs lowercase T and F in the words "true" and "false". Unlike a regex it will not handle "T" or "F" by itself. The only detractor is that the usage of "zero?" might be confusing to people who aren't familiar with that method.
    – emery
    Aug 11, 2021 at 23:32
2

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.

0

Close to what is already posted, but without the redundant parameter:

class String
    def true?
        self.to_s.downcase == "true"
    end
end

usage:

do_stuff = "true"

if do_stuff.true?
    #do stuff
end
0

This function works for any input:

def true?(value)
 ![false, 0, "0", "f", "F", "false", "FALSE", "off", "OFF"].include? value
end

then you have:

true?(param) #returns true or false 
-1

You could just add !! before the variable:

!!test_string
4
  • Please make the additional insight more obvious which you contribute beyond stackoverflow.com/a/42785735/7733418 Also, ...
    – Yunnosch
    Jan 24 at 10:29
  • While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
    – Yunnosch
    Jan 24 at 10:29
  • Yeah this is interesting; I gave it an upvote because I have never used !! before and am glad to know about it. I agree that an explanation as to why it works to meet the original question would be good.
    – emery
    Feb 10 at 18:51
  • 1
    !! combined with any string will be true, so this will not work. All strings (even empty strings) are truthy. !!"true" and !!"false" are both true
    – Jon Evans
    Jun 15 at 16:05

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.