"HELLO" But h...">

A general way to replace an object in its own method

Using the lines you can do the following:

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

But how would I write my own method?

Something like (although this does not work explicitly):

class MyClass
  def positify!
    self = [0, self].max
  end
end

I know there are some tricks that can be used in String, but what if I try to do something similar for Object?

+5
source share
4 answers

Well, the method upcase!does not change the identifier of the object, it only changes the internal structure ( s.object_id == s.upcase!.object_id).

, , , . AFAIK, , , , positify!, , - , ! .

+4

(, Numeric, Symbol,...), , .

, Object , .

( 42) , SimpleDelegator. quacks_like_an_int 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

, :

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
+7

( =) , . Ruby-, , Ruby. Binding , . , .

, self = , , a = "string"; a = "another string", ; . , , , ; , .

+2

self, -, . , , case, .

: Ruby self Float

There is a trick here, which is a job, which is to write you a class as a wrapper around another object. Then your wrapper class can optionally replace the wrapped object. I hesitate to say that this is a good idea.

+2
source

All Articles