Tag: 设定者

是否有可能让class.property = x返回x以外的东西?

假设我有一个Ruby类: class MyClass def self.property return “someVal” end def self.property=(newVal) # do something to set “property” success = true return success # success is a boolean end end 如果我尝试执行MyClass.property=x ,则整个语句的返回值始终为x。 许多基于C语言/灵感的语言中的约定是返回布尔“成功”值 – 是否可以使用Ruby中的“equals语法”为setter执行此操作? 此外 – 如果不可能,为什么不呢? 允许“等于设定者”操作返回值是否有任何可以想象的缺点?