The main use case is allowing the user to use some methods on an internal ivar within a class, without exposing the actual ivar to the user.
Example
class Validator
def valid?(value : String)
value == "foo"
end
end
class WithoutDelegate
getter validator : Validator = Validator.new
end
# Notice in this case you have to make a getter
# to the validator class
pp WithoutDelegate.new.validator.valid? "foo"
class WithDelegate
delegate :valid?, to: @validator
@validator : Validator = Validator.new
end
# Notice in this case we can keep the validator
# instance private and just expose a select few
# methods on it. Also notice the UX is nicer
# since you dont have to have that extra
# .validator in there
pp WithDelegate.new.valid? "foo"
In the example you provided they’re similar, but the StringWrapper
is only allowing a subset of String
's methods to be used. If you tried to do wrapper.tr("l","")
it wouldn’t compile since StringWrapper
doesn’t have a tr
method defined, and you’re not delegating it to the internal string.