https://github.com/sam0x17/truthy
Adds intelligent to_b (to_boolen) to all objects in crystal
https://github.com/sam0x17/truthy
boolean crystal crystal-language crystal-shard crystal-shards shard truthy
Last synced: 6 months ago
JSON representation
Adds intelligent to_b (to_boolen) to all objects in crystal
- Host: GitHub
- URL: https://github.com/sam0x17/truthy
- Owner: sam0x17
- License: mit
- Created: 2018-07-29T22:32:55.000Z (about 7 years ago)
- Default Branch: master
- Last Pushed: 2019-02-02T15:07:33.000Z (over 6 years ago)
- Last Synced: 2025-02-13T08:14:47.754Z (8 months ago)
- Topics: boolean, crystal, crystal-language, crystal-shard, crystal-shards, shard, truthy
- Language: Crystal
- Size: 13.7 KB
- Stars: 2
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# truthy
Truthy patches all objects in crystal with a `to_b` (to boolean) method that will intelligently return
a boolean based on the value of the object. This will differ from `!!(expr)` in a number of cases
including the handling of `""` and `'\0'` as `false`, and proper handling of class instances and arrays (an empty array => false, an array with elements => true).`expr.to_b` will always return `true` or `false` no matter what you pass to it. `!!(expr)` is used
as a fallback for any language features that are not explictly covered.An alias is provided so that you can also use `*.truthy?` if you think this makes more sense than
`to_b`. Both methods function in exactly the same way and are interchangable.## Installation
Add this to your application's `shard.yml`:
```yaml
dependencies:
truthy:
github: sam0x17/truthy
```## Usage
```crystal
require "truthy"# Booleans
true.to_b # => true
false.to_b # => false# Objects
nil.to_b # => false
SomeClass.new.to_b # => true# Strings / Characters
"".to_b # => false
"hey".to_b # => true
'\0'.to_b # => false
'c'.to_b # => true
"0".to_b # => false
"1".to_b # => true
"200".to_b # => true
"1.0".to_b # => true
"-1.0".to_b # => false
"true".to_b # => true
"false".to_b # => false
"yes".to_b # => true
"no".to_b # => false
"nil".to_b # => false
"null".to_b # => false
"none".to_b # => false
"True".to_b # => true
"[]".to_b # => false
"{}".to_b # => false# Integers
0.to_b # => false
-1.to_b # => false
1.to_b # => true
10.to_b # => true
0_i64.to_b # => false
1_i8.to_b # => true
-1_i16.to_b # => false
0_u64.to_b # => false
3_u16.to_b # => true# Floats
0.0.to_b # => false
1.0.to_b # => true
0.001.to_b # => true
-0.001.to_b # => false
-1.0.to_b # => false
23.342.to_b # => true# Arrays
[1, 2, 3].to_b # => true
([] of Int32).to_b # => false# truthy? alias
true.truthy? # => true
false.truthy? # => false
0.truthy? # => false
1.truthy? # => true
```