是否可以让 class.property = x 返回 x 以外的其他内容? [英] Is it possible to have class.property = x return something other than x?
问题描述
假设我有一个 Ruby 类:
Let's say I have a Ruby class:
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 执行此操作?
If I try and do MyClass.property=x
, the return value of the whole statement is always x. It is a convention in a lot of C-based/inspired languages to return a boolean "success" value - is it possible to do this for a setter using the "equals syntax" in Ruby?
此外 - 如果这是不可能的,为什么不呢?允许equals setter"操作返回值有什么可以想象的缺点吗?
Furthermore - if this isn't possible, why not? Is there any conceivable downside to allowing an "equals setter" operation return a value?
推荐答案
一个缺点是你会打破链式赋值语义:
One downside is that you would break the chained assignment semantics:
$ irb
irb(main):001:0> x = y = 3
=> 3
irb(main):002:0> p x
3
=> nil
irb(main):003:0> p y
3
=> nil
irb(main):004:0>
考虑:
x = MyClass.property = 3
然后 x
将采用 true
如果这如您所料(右结合).对于使用您的界面并习惯于典型语义的人来说,这可能是一个惊喜.
Then x
would take true
if this worked as you had expected (right-associativity). That could be a surprise for people using your interface and used to the typical semantics.
你也让我想到了并行分配,例如:
You also got me thinking about parallel assignment, eg:
x, y = 1, 2
显然该表达式的返回值是具体实现...我想我不会链接并行分配:)
Apparently the return value from that expression is implementation specific... I guess I won't be chaining parallel assignments :)
好问题!
这篇关于是否可以让 class.property = x 返回 x 以外的其他内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!