I’m starting to see
delegate used, and I’m trying to understand its use case.
What is the difference between
class StringWrapper def initialize(@string : String) end delegate downcase, to: @string delegate gsub, to: @string delegate empty?, capitalize, to: @string delegate :, to: @string end wrapper = StringWrapper.new "HELLO" wrapper.downcase # => "hello" wrapper.gsub(/E/, "A") # => "HALLO" wrapper.empty? # => false wrapper.capitalize # => "Hello"
wrapper = "HELLO" pp wrapper.downcase pp wrapper.gsub(/E/, "A") pp wrapper.empty? pp wrapper.capitalize
class String2 property s : String def initialize(@s : String) end end stringer = String2.new("HELLO") pp stringer.s.downcase pp stringer.s.gsub(/E/, "A") pp stringer.s.empty? pp stringer.s.capitalize
Delegate methods to to .
Okay? But why? When you can just use string literal syntax
" " and call the string methods. Or, use a class with a
s property (String type), that uses the innate
String methods. If you need a wrapper, the developer can use method overloading (or implement their own methods!) on their class, which follows OOP design.
What am I missing here?