Skip to content

Instantly share code, notes, and snippets.

@kares
Created July 23, 2019 16:53
Show Gist options
  • Save kares/8a57d805d3fb8c6580e193974d174bb5 to your computer and use it in GitHub Desktop.
Save kares/8a57d805d3fb8c6580e193974d174bb5 to your computer and use it in GitHub Desktop.
`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