Peter Heinemeier Peter Heinemeier - 2 years ago 123
Ruby Question

Optional type in Ruby / Rails similar to Swift

I know that there is nothing in Ruby that is similar to the

type in swift, however in Rails there is
where you can pass the method and its arguments as symbols, isn't that the equivalent to an
type, if not what would an
type in Ruby look like?

Answer Source

Well no, try is not the same as optional since it does not wrap the original object in a new type and return that type, thus making the series of method calls chainable. try return nil not Optional(nil).

To see how one would go about implementing the optional type in ruby, take a look at a little gem called nil_be_gone I have just open sourced, that gives you an Optional that you can wrap objects with. It implements method_missing to check whether the value of the Optional is nil and if so simply return another Optional wrapped nil value, otherwise it calls the method on the object and wraps it again.

nil_be_gone implements bind as and_then which allows you to chain operations on Optional types, it's return methods which retrieves the value from Optional is value and the unit operation which wraps an object in the monad is defined by self.from_value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download