Create a new class and override the method_missing method
class BackwardsString
def initialize(s)
@s = s
end
def method_missing(m, *args, &block)
result = @s.send(m, *args, &block)
result.respond_to?(:to_str) ? BackwardsString.new(result) : result
end
def to_s
@s.reverse
end
def inspect
to_s
end
end
s = BackwardsString.new("I'm backwards.") # => .sdrawkcab m'I
s.size # => 14
s.upcase # => .SDRAWKCAB M'I
s.reverse # => I'm backwards.
s.no_such_method
# NoMethodError: undefined method 'no_such_method' for "I'm backwards.":String
Related examples in the same category