Skip to content

Instantly share code, notes, and snippets.

@kares kares/to_bool.rb
Created Jul 23, 2019

Embed
What would you like to do?
`params[:foo].to_bool`, `ENV['bar'].to_bool` and others
# frozen_string_literal: true
class Object
# Convert to a boolean value (special cased for String/Numeric).
# @return [Boolean] false for nil and false ('true', '1' return true and 0 returns false)
# @see String#to_bool
# @see Numeric#to_bool
def to_bool
!!self
end
end
class String
# @return [Boolean] 'true' and '1' are considered truthy
def to_bool
'true'.casecmp(self).zero? || '1'.eql?(self)
end
end
class Numeric
# @return [Boolean] false for 0, true otherwise
def to_bool
!zero?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.