Guy>      a = Complex(0, 1)
Guy>      b = Complex(1, 0)
Guy>      c = a + b
Guy>      puts c

Stephen> Is there any way to make an object return its value
Stephen> on a simple reference rather than having to make
Stephen> an explicit method/accessor call?

I've also been wondering about how to do the Quantity Pattern (AKA the Whole
Value Pattern) in ruby, i.e. making an object act transparently as an
immediate value.

The use of a Factory Method (like in complex.rb) indeed makes it nice, but
you still have to explicitly copy the object when returning the value from a
method or passing it as parameter to another method. Otherwise the object is
not 100% value-based.

I wonder though if it has any true significance. I cannot remember any good
examples where it would be significant. In other words: I don't think you
need the flexibility which comes with an added complexity.

Any thoughts?

Simple example:

def Quantity(value)
  Quantity.new(value)
end

class Quantity
  attr_reader :value

  def initialize(value=nil)
    @value = value
  end

  def to_s
    self.value.to_s
  end

  def to_i
    self.value
  end

  def +(other)
    Quantity(self.value+other.value) #explicit copy-construction
  end

  def -(other)
    Quantity(self.value-other.value) #explicit copy-construction
  end

end

a = Quantity(10)
b = Quantity(7)
c = a+b

print "#{a} + #{b} = #{c}\n" # -> 10 + 7 = 17

# BUT - here you need explicitly to convert Quantity to Integer:

print "%d + %d = %d \n" % [a.to_i, b.to_i, c.to_i] # -> 10 + 7 = 17

# ... and explicit copy-by-value parameter passing:

def printlnQuantity(quantity)
  print "#{quantity}\n"
end

printlnQuantity(a+b) # -> 17
printlnQuantity(Quantity(b)) # -> 7

-----

Dennis Decker Jensen