If Atom
, String
(BitString
), Integer
and Float
values wanna be a boolean value, they can using to_boolean/1
function.
The package can be installed by adding wannabe_bool
to your list of dependencies in mix.exs
:
def deps do
[
{:wannabe_bool, "~> 0.1.3"}
]
end
The is_boolean/1
function is implemented for Atom
, BitString
, Integer
and Float
types.
You can use is_boolean/1
function importing WannabeBool
protocol:
iex> import WannabeBool
iex>
iex> to_boolean("true")
true
Or calling it in WannabeBool
protocol directly:
iex> WannabeBool.to_boolean("true")
true
Each type has its own "truthy values".
Returns true
if the given string is one of these values: "t"
, "true"
, "on"
, "y"
, "yes"
, "1"
.
Otherwise, returns false
.
Trailling spaces and letter cases are ignored.
iex> to_boolean("t")
true
iex> to_boolean("T")
true
iex> to_boolean("true")
true
iex> to_boolean("TRUE")
true
iex> to_boolean("on")
true
iex> to_boolean("ON")
true
iex> to_boolean("y")
true
iex> to_boolean("yes")
true
iex> to_boolean("YES")
true
iex> to_boolean("1")
true
iex> to_boolean(" t ")
true
iex> to_boolean(" T ")
true
iex> to_boolean(" true ")
true
iex> to_boolean(" TRUE ")
true
iex> to_boolean(" on ")
true
iex> to_boolean(" ON ")
true
iex> to_boolean(" y ")
true
iex> to_boolean("Y")
true
iex> to_boolean(" Y ")
true
iex> to_boolean(" yes ")
true
iex> to_boolean(" YES ")
true
iex> to_boolean(" 1 ")
true
iex> to_boolean("false")
false
iex> to_boolean("whatever")
false
iex> to_boolean("")
false
The same as my_atom |> to_string() |> to_boolean()
.
true
and false
obvisouly returns true
and false
respectively. :)
nil
returns false
.
iex> to_boolean(:"t")
true
iex> to_boolean(:"true")
true
iex> to_boolean(:"on")
true
iex> to_boolean(:"y")
true
iex> to_boolean(:"yes")
true
iex> to_boolean(:"1")
true
iex> to_boolean(:"false")
false
iex> to_boolean(:"whatever")
false
iex> to_boolean(:"")
false
iex> to_boolean(true)
true
iex> to_boolean(false)
false
iex> to_boolean(nil)
false
Returns false
if the given integer is zero. Otherwise, returns true
.
iex> to_boolean(0)
false
iex> to_boolean(1)
true
iex> to_boolean(2)
true
iex> to_boolean(-1)
true
iex> to_boolean(-2)
true
Returns false
if the given float is zero. Otherwise, returns true
.
iex> to_boolean(0.0)
false
iex> to_boolean(0.1)
true
iex> to_boolean(1.0)
true
iex> to_boolean(-0.1)
true
iex> to_boolean(-1.0)
true
For other not implemented types a Protocol.UndefinedError
is raised.
iex> to_boolean([])
** (Protocol.UndefinedError) protocol WannabeBool not implemented for []. This protocol is implemented for: Atom, BitString, Float, Integer
The full documentation is available at https://hexdocs.pm/wannabe_bool.
See the contributing guide.
Wannabe Bool is released under the Apache 2.0 License. See the LICENSE file.
Copyright © 2018-2021 Fernando Hamasaki de Amorim