Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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?

Furthermore - if this isn't possible, why not? Is there any conceivable downside to allowing an "equals setter" operation return a value?

like image 600
Nick Forge Avatar asked Apr 02 '09 07:04

Nick Forge


1 Answers

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!

like image 150
Martin Carpenter Avatar answered Oct 21 '22 00:10

Martin Carpenter