Generic way to replace an object in it's own method

后端 未结 4 847
别跟我提以往
别跟我提以往 2021-01-13 04:51

With strings one can do this:

a = \"hello\"
a.upcase!
p a #=> \"HELLO\"

But how would I write my own method like that?

Somethin

4条回答
  •  广开言路
    2021-01-13 05:04

    Many classes are immutable (e.g. Numeric, Symbol, ...), so have no method allowing you to change their value.

    On the other hand, any Object can have instance variables and these can be modified.

    There is an easy way to delegate the behavior to a known object (say 42) and be able to change, later on, to another object, using SimpleDelegator. In the example below, quacks_like_an_int behaves like an Integer:

    require 'delegate'
    quacks_like_an_int = SimpleDelegator.new(42)
    quacks_like_an_int.round(-1) # => 40
    quacks_like_an_int.__setobj__(666)
    quacks_like_an_int.round(-1) # => 670
    

    You can use it to design a class too, for example:

    require 'delegate'
    class MutableInteger < SimpleDelegator
      def plus_plus!
        __setobj__(self + 1)
        self
      end
    
      def positify!
        __setobj__(0) if self < 0
        self
      end
    end
    
    i = MutableInteger.new(-42)
    i.plus_plus! # => -41
    i.positify! # => 0
    

提交回复
热议问题