Skip to content

Commit

Permalink
Case expression tests
Browse files Browse the repository at this point in the history
  • Loading branch information
rap1ds committed Jul 23, 2014
1 parent e8a10a9 commit 6d72dfd
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 0 deletions.
49 changes: 49 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,55 @@ Maybe("I'm a value").upcase => #<Maybe::Some:0x007ffe198e6128 @v
Maybe(nil).upcase => None
```

### Case expression

Maybe implements threequals method `#===`, so it can be used to match the type in case expressions:

```ruby
value = Maybe([nil, 1, 2, 3, 4, 5, 6].sample)

case value
when Some
puts "Got Some value: #{value.get}"
when None
puts "Got None"
end
```

If the type is Some, you can also match the value of the Some:

```ruby
value = Maybe([nil, 1, 2, 3, 4, 5, 6].sample)

case value
when Some((1..3))
puts "Got a low number: #{value.get}"
when Some((4..6))
puts "Got a high number, yey! #{value.get}"
when None
puts "Got nothing"
end
```

You might not known this, but Proc class aliases #=== to the #call method. That means that you can use Procs and lambdas
in case expressions. It works also nicely with Maybe:

```ruby
even? = ->(a) { a % 2 == 0 }
odd? = ->(a) { a % 2 != 0 }

value = Maybe([nil, 1, 2, 3, 4, 5, 6].sample)

case value
when Some(even?)
puts "Got even value: #{value.get}"
when Some(odd?)
puts "Got odd value: #{value.get}"
when None
puts "Got None"
end
```

## Examples

Instead of using if-clauses to define whether a value is a `nil`, you can wrap the value with `Maybe()` and threat it the same way whether or not it is a `nil`
Expand Down
37 changes: 37 additions & 0 deletions spec/spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,43 @@
end
end

describe "case expression" do
def test_case_when(case_value, match_value, non_match_value)
value = case case_value
when non_match_value
false
when match_value
true
else
false
end

expect(value).to be_true
end

it "matches Some" do
test_case_when(Maybe(1), Some, None)
end

it "matches None" do
test_case_when(Maybe(nil), None, Some)
end

it "matches to integer value" do
test_case_when(Maybe(1), Some(1), Some(2))
end

it "matches to range" do
test_case_when(Maybe(1), Some((0..2)), Some((2..3)))
end

it "matches to lambda" do
even = ->(a) { a % 2 == 0 }
odd = ->(a) { a % 2 == 1 }
test_case_when(Maybe(2), Some(even), Some(odd))
end
end

describe "to array" do
it "#to_ary" do
a, _ = Maybe(1)
Expand Down

0 comments on commit 6d72dfd

Please sign in to comment.