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

后端 未结 4 844
别跟我提以往
别跟我提以往 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条回答
  •  -上瘾入骨i
    2021-01-13 04:59

    Assignment, or binding of local variables (using the = operator) is built-in to the core language and there is no way to override or customize it. You could run a preprocessor over your Ruby code which would convert your own, custom syntax to valid Ruby, though. You could also pass a Binding in to a custom method, which could redefine variables dynamically. This wouldn't achieve the effect you are looking for, though.

    Understand that self = could never work, because when you say a = "string"; a = "another string" you are not modifying any objects; you are rebinding a local variable to a different object. Inside your custom method, you are in a different scope, and any local variables which you bind will only exist in that scope; it won't have any effect on the scope which you called the method from.

提交回复
热议问题