编辑:对于那些批评我替换 self
的意图的人,您可以自由单击后退按钮,继续按照您自己的意见进行开发,让我按照我的意见进行开发:)
我想知道是否有办法完全删除 self
引用的对象并用新实例替换它。
示例:
def refresh_from_server!
self = newly_fetched_object_from_server
end
我不想返回
新对象。
看来我必须构建自己的复制界面并调用 self.copy_from(other_object)
但也许有人有很棒的 ruby bit 可以分享,效果更好!
--编辑
由于有些人似乎对这个问题不清楚,我希望 instance.my_method!
将 instance
完全替换为该类的新实例
例如假设我们有一个类
class Counter
attr_accessor :count
def initialize
count = 0
end
def reset!
# This is what I want to achieve.
# Obviously in this case it would be trivial to write `self.count = 0`
# Or return a new value
# But I have a much more complex object in real life
# which copying would not be trivial
# All I'm looking for is a bit of stylistic sugar to make my code look cooler
# If it doesn't exist, I would love to know why
self = Counter.new
end
def up
count += 1
end
end
最佳答案
不,您不能替换self
。您只能更改其部分/全部状态,但对象引用将保持不变。
无论如何,你为什么要这样做?如果您只想利用初始化逻辑(在我看来就是这种情况),一些重构会有所帮助:只需从两个地方调用一个共享方法。
class Counter
attr_accessor :count
def initialize
init_state
end
def reset!
init_state
end
def up
self.count += 1
end
private
def init_state
self.count = 0
end
end
关于ruby - 为什么不能在 Ruby 中替换 self?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32210092/