Is it possible to have class.property = x return something other than x?

前端 未结 3 434
野的像风
野的像风 2020-12-04 01:42

Let\'s say I have a Ruby class:

class MyClass
  def self.property
    return \"someVal\"
  end

  def self.property=(newVal)
    # do something to set \"prop         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 01:52

    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> 
    

    Consider:

    x = MyClass.property = 3
    

    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 :)

    Nice question!

提交回复
热议问题