Ruby 中的 Setter 方法别名
Ruby 中的别名方法相对简单。一个人为的示例:
class Person
def name
puts "Roger"
end
end
class User < Person
alias :old_name :name
def name
old_name
puts "Staubach"
end
end
在这种情况下,运行 User.new.name
将输出:
Roger
Staubach
That Works as expected。但是,我正在尝试为 setter 方法添加别名,这显然并不简单:
class Person
def name=(whatever)
puts whatever
end
end
class User < Person
alias :old_name= :name=
def name=(whatever)
puts whatever
old_name = whatever
end
end
这样,调用 User.new.name = "Roger"
将输出:
Roger
看来新的别名方法被调用,但原始版本没有。
这是怎么回事?
ps - 我知道 super
,为了简洁起见,我不想在这里使用它
Aliasing methods in Ruby is relatively straight-forward. A contrived example:
class Person
def name
puts "Roger"
end
end
class User < Person
alias :old_name :name
def name
old_name
puts "Staubach"
end
end
In this case, running User.new.name
will output:
Roger
Staubach
That works as expected. However, I'm trying to alias a setter method, which is apparently not straight-forward:
class Person
def name=(whatever)
puts whatever
end
end
class User < Person
alias :old_name= :name=
def name=(whatever)
puts whatever
old_name = whatever
end
end
With this, calling User.new.name = "Roger"
will output:
Roger
It appears that the new aliased method gets called, but the original does not.
What is up with that?
ps - I know about super
and let's just say for the sake of brevity that I do not want to use it here
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为当 Ruby 缺少对象引用时,它不会将
old_name =whatever
识别为方法调用。尝试:改为(注意
self.
)I don't think Ruby will recognize
old_name = whatever
as a method call when it lacks an object reference. Try:instead (note the
self.
)试试这个:
Try this:
你需要
self.old_name =whatever
,只是简单的old_name
是本地的。You need
self.old_name = whatever
, just plainold_name
is a local.别名是否必须是 setter?
Does the alias have to be a setter?