Class: Monadic::Maybe

Inherits:
Object show all
Includes:
Monad
Defined in:
lib/monadic/maybe.rb

Direct Known Subclasses

Just, Nothing

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Monad

#==, #bind, #fetch, #flat_map, #initialize, #join, #map, #to_ary, #to_s

Class Method Details

.unit(value) ⇒ Object



5
6
7
8
# File 'lib/monadic/maybe.rb', line 5

def self.unit(value)
  return Nothing if value.nil? || (value.respond_to?(:empty?) && value.empty?)
  return Just.new(value)
end

Instance Method Details

#empty?Boolean

Returns true if the underlying object responds to #empty?, false otherwise.

Returns:

  • (Boolean)

    true if the underlying object responds to #empty?, false otherwise



15
16
17
# File 'lib/monadic/maybe.rb', line 15

def empty?
  @value.respond_to?(:empty?) && @value.empty?
end

#select(proc = nil, &block) ⇒ Failure, Success

Returns the Maybe Monad filtered with the block or proc expression.

Returns:

  • (Failure, Success)

    the Maybe Monad filtered with the block or proc expression



20
21
22
23
24
25
# File 'lib/monadic/maybe.rb', line 20

def select(proc = nil, &block)
  func = (proc || block)
  return Maybe(@value.select {|v| func.call(v) }) if @value.respond_to? :select
  return Nothing unless func.call(@value)
  return self
end

#truly?true, false

Returns true if the underlying value is true.

Returns:

  • (true, false)

    true if the underlying value is true



28
29
30
# File 'lib/monadic/maybe.rb', line 28

def truly?
  !!@value == true
end