class Dry::Monads::Maybe::Some
Represents a value that is present, i.e. not nil.
@api public
Private Class Methods
Shortcut for Some()
@example include Dry::Monads[:maybe] def call Some[200, {}, ['ok']] # => Some([200, {}, ['ok']]) end
@api public
# File lib/dry/monads/maybe.rb, line 99 def self.[](*value) new(value) end
# File lib/dry/monads/maybe.rb, line 103 def initialize(value = Undefined) raise ArgumentError, "nil cannot be some" if value.nil? super() @value = Undefined.default(value, Unit) end
Private Instance Methods
Accepts a block and runs it against the wrapped value. If the block returns a trurhy value the result is self, otherwise None
. If no block is given, the value serves and its result.
@param with [#call] positional block @param block [Proc] block
@return [Maybe::None, Maybe::Some
]
# File lib/dry/monads/maybe.rb, line 167 def filter(with = Undefined, &block) block = Undefined.default(with, block || IDENTITY) if block.(@value) self else Monads.None() end end
Does the same thing as bind
except it also wraps the value in an instance of Maybe::Some
monad. This allows for easier chaining of calls.
@example
Dry::Monads.Some(4).fmap(&:succ).fmap(->(n) { n**2 }) # => Some(25)
@param args [Array<Object>] arguments will be transparently passed through to bind
@return [Maybe::Some, Maybe::None
] Wrapped result, i.e. nil will be mapped to None
,
other values will be wrapped with Some
# File lib/dry/monads/maybe.rb, line 121 def fmap(...) next_value = bind(...) if next_value.nil? if self.class.warn_on_implicit_nil_coercion Core::Deprecations.warn( "Block passed to Some#fmap returned `nil` and was chained to None. "\ "This is literally an unlawful behavior and it will not be supported in "\ "dry-monads 2. \nPlease, replace `.fmap` with `.maybe` in places where you "\ "expect `nil` as block result.\n"\ "You can opt out of these warnings with\n"\ "Dry::Monads::Maybe.warn_on_implicit_nil_coercion false", uplevel: 0, tag: :"dry-monads" ) end Monads.None() else Some.new(next_value) end end
Does the same thing as bind
except it also wraps the value in an instance of the Maybe
monad. This allows for easier chaining of calls.
@example
Dry::Monads.Some(4).maybe(&:succ).maybe(->(n) { n**2 }) # => Some(25) Dry::Monads.Some(4).maybe(&:succ).maybe(->(_) { nil }) # => None()
@param args [Array<Object>] arguments will be transparently passed through to bind
@return [Maybe::Some, Maybe::None
] Wrapped result, i.e. nil will be mapped to None
,
other values will be wrapped with Some
# File lib/dry/monads/maybe.rb, line 154 def maybe(...) Maybe.coerce(bind(...)) end
Converts to Sucess(value!)
@param fail [#call] Fallback value @param block [Proc] Fallback block @return [Success<Any>]
# File lib/dry/monads/result.rb, line 408 def to_result(_fail = Unit) Result::Success.new(@value) end
@return [String]
# File lib/dry/monads/maybe.rb, line 178 def to_s if Unit.equal?(@value) "Some()" else "Some(#{@value.inspect})" end end