Puts box.dup.enlarge(4, 5) -- unexpected result

Hello,

I wonder why the statement “puts box.dup.enlarge(4, 5)” below gives
output 8 instead of (0, 1, 6, 8).

Thanks, Stefan S.

stefan@AMD64X2 ~/pet $ cat btest.rb
#!/usr/bin/ruby -w
module Bounding
class Box
attr_accessor :x1, :y1, :x2, :y2
def initialize(x1, y1, x2, y2)
@x1, @x2 = [x1, x2].minmax
@y1, @y2 = [y1, y2].minmax
end
def to_s
“(#{@x1}, #{@y1}, #{@x2}, #{@y2})”
end
def enlarge(x, y)
if x < 0 then @x1 += x else @x2 += x end
if y < 0 then @y1 += y else @y2 += y end
end
end
end # Bounding

box = Bounding::Box.new(0, 1, 2, 3)
puts box

#this works as exspected
nb = box.dup
nb.enlarge(4, 5)
puts nb

#this works NOT as expected
puts box.dup.enlarge(4, 5)

stefan@AMD64X2 ~/pet $ ruby btest.rb
(0, 1, 2, 3)
(0, 1, 6, 8)
8

A method returns the last evaluated expression. In your case thats @y2
+= 5
(which has the result 8).
You could do something like this:
def enlarge(x,y)
#your code

self
end

so the method returns the box itself and not the result of calculationg
new
coordinates.

2011/4/12 Stefan S. [email protected]

On Tue, 2011-04-12 at 21:55 +0900, Gunther D. wrote:

coordinates.

Thanks!